[英]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。您可以通過兩種方式解決此問題:
int
。 這將導致輸入存儲為 1,因此比較將導致計數增加。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.