[英]Why am I getting the wrong output for this C++ code? (one of the problem of hackerrank)
[英]Getting error on submission for Kattis "OddGnome" problem. I am getting the right output locally, what is wrong with my code? C++
#include <stdio.h>
int main(){
int n, g, i;
scanf("%d\n", &n);
while(n--) {
int l = -1;
int c = 1;
scanf("%d", &g);
while(g--) {
scanf("%d", &i);
if (l == -1) l = i;
else if (i - 1 != l) break;
else l++;
c++;
}
fflush(stdin);
printf("%d\n", c);
}
}
我正確地得到了所有的輸出,所以我不知道可能出了什么問題。 另一方面,Kattis 接受了我在 GitHub 上找到的以下代碼,並且輸出與我的代碼完全相同。 如果有人能向我解釋什么是錯的或為什么 Kattis 拒絕我的代碼,我將不勝感激。
#include <bits/stdc++.h>
using namespace std;
int main()
{
//Initialize n and g, take in n
int n, g;
cin >> n;
//Iterate n times
while (n--)
{
//Take in g, initialize empty vector of size g
cin >> g;
vector<int> gnomes(g);
//Take in all the gnomes
for (int i = 0; i < g; i++) cin >> gnomes[i];
//Iterate through without the beginning or end since king won't be there
for (int i = 1; i < g-1; i++)
{
//Must break the order, and if you remove it the gnomes around it should be in order
if (gnomes[i] < gnomes[i-1] || gnomes[i] > gnomes[i+1] && gnomes[i-1] < gnomes[i+1])
{
//Output the 1 based index, so add 1
cout << i+1 << endl;
//And exit to the next group
break;
}
}
}
}
首先,如果您使用的是 C++,請使用 C++,而不是 C!
正如所指出的, fflush(stdin)
是未定義的行為。 相反,您可以使用std::getline
來咀嚼該行的其余部分。
除此之外,您的邏輯看起來不錯,即使它與過度殺傷的 C++ 解決方案不同。 正如您似乎推斷的那樣,無需檢查i + 1
或使用向量。
不過,我建議使用更清晰的命名和空格約定。
這是一個 C 解決方案,使用scanf
讀取該行的其余部分:
#include <stdio.h>
int main() {
int n;
scanf("%d\n", &n);
for (int i = 0; i < n; i++) {
int previous = -1;
int g;
scanf("%d", &g);
for (int j = 0; j < g; j++) {
int current;
scanf("%d", ¤t);
if (previous >= 0 && previous + 1 != current) {
printf("%d\n", ++j);
for (; j < g; j++) {
scanf("%d", ¤t);
}
break;
}
previous = current;
}
}
}
這是一個使用bits/stdc++.h
並using namespace std;
,這是競爭性編程中的常見習語,但絕不應在任何應用程序代碼中使用。
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int g;
cin >> g;
int previous = -1;
for (int j = 0; j < g; j++) {
int current;
cin >> current;
if (previous >= 0 && previous + 1 != current) {
cout << (1 + j) << "\n";
string s;
getline(cin, s);
break;
}
previous = current;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.