繁体   English   中英

我对“团队”codeforces 任务有疑问,不明白为什么我的 c++ 代码有效而无效

[英]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;
}

codeforces 上的任务名称是“团队”,看起来很简单,但我的代码在第五次测试中不起作用。 我们需要找出一组人可以解决多少个任务(如果有 2 个或多个数字 1,那么他们可以解决它,如果更少,那么他们不能。输入是:

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

和一个 output 应该是 1(因为只有一行有超过 2 个数字的 1,但它给了我 4,如果我没记错的话。找不到错误,你能帮我吗?

这是因为您正在检查 j 是否等于 1,而不是检查输入中的值是否等于 1。将if(j == 1)更改为if(matrix[i][j] == 1) 此外,您需要在外部 for 循环内设置count = 0 (在if(count >= 2)块之后),否则您的计数将继续增加。

编辑:正如 Johnny Mopp 所指出的,您使用的是char矩阵而不是 int。 现在了解 chars 在 C/C++ 中存储为它们的 ASCII 值,这意味着(char)1存储为 49。您可以通过两种方式解决此问题:

  1. 将矩阵声明为int 这将导致输入存储为 1,因此比较将导致计数增加。
  2. 在不更改声明的情况下,使用if(matrix[i][j] == '1')进行比较。 这导致 char 1 与 char 1 进行比较,即 49 等于 49。同样,您的计数将增加。

这是我在 Python 3 中的答案(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)

只需查看我在 Python 中而不是在 C++ 中所做的算法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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