简体   繁体   中英

I have a problem with “team” codeforces task, don't understand why my c++ code does work and doesn't

#include <iostream>
using namespace std;

int main() {

    int n;
    cin >> n;   // number of problems
    int solvableProblems = 0;
    char matrix[n][3];
    int count = 0;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 3; j++) {
            cin >> matrix[i][j];
        }   
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 3; j++) {
            if (j == 1) {
                count++;
            }
        }
        if (count >= 2) {
            solvableProblems++;
        }   
    }

    cout << solvableProblems;


return 0;
}

The task name is "team" on codeforces, looks like an easy problem, but my code does not work on the fifth test. we need to find how many tasks can a group of people solve(if there're 2 or more digits of 1 then, they can solve it, if less, then they can't. the input is:

5
1 0 0
0 1 0
1 1 1
0 0 1
0 0 0

and an output should be 1(cause there is only one row with more than 2 digits of one, but it gives me 4, if i'm not mistaken. can't find bug, can you help me?

It's because you are checking whether j is equals to 1 rather than checking whether the value in the input is equal to 1. Change if(j == 1) with if(matrix[i][j] == 1) . Also, you need to set count = 0 inside the outer for loop (after the if(count >= 2) block), otherwise your count will keep on increasing.

Edit: As pointed out by Johnny Mopp, you have used char matrix instead of int. Now understand that chars are stored in C/C++ as their ASCII value, which means (char)1 is stored as 49. You can solve this by two ways:

  1. declare the matrix as int . This will result in input being stored as 1 and hence the comparison will result in an increment of count.
  2. Without changing the declaration, compare using if(matrix[i][j] == '1') . This results in char 1 being compared to char 1, ie, 49 equals 49. Again, your count will increment.

Here is my answer in Python 3 ( Answer accepted by Codeforces )

n = int(input())
x=0
for i in range(n):
    p, v, t = input().split()
    p, v, t = [int(p), int(v), int(t)]
    if (p+v+t)>1:
        x+=1
print(x)

Just see the algorithm as I have done it in Python not in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM