我目前正在解决UVa 问题编号。10038。所以,为了调试我的代码,我去了uDebug。并发现我的代码几乎完整,但有一些例外。
我希望审查以下代码。任何编辑建议都会有所帮助。
我曾尝试使用 while 循环(在代码的近端)而不是 if 语句,但这会冻结输入。
/*#include <iostream>, <vector>, <algorithm>, <functional>*/
int main(){
/*Declaring everything required*/
int n, num, diff;
bool is_jolly;
vector<int> numbers, differences;
while(cin >> n){
/*Deleting all elements before working with them*/
numbers.clear();
differences.clear();
/*A sequence of single number is always JOLLY*/
/*Taking in all the numbers*/
for(int i = 0; i < n; i++){
cin >> num;
numbers.push_back(num);
}
/*Calculating the absolute value of those*/
for(int i = 1; i < n; i++){
diff = abs(numbers[i] - numbers[i - 1]);
differences.push_back(diff);
}
/*Sorting the differences in descending order*/
if(differences.size() > 1){
sort(differences.begin(), differences.end(), greater<int>());
}
/*Creating a iterator for checking if the value reached one through n - 1*/
int k = n - 1;
for(int i = 0; i < differences.size(); i++){
if(differences[i] == k){/*Tried the while loop here*/
is_jolly = true;/*<-----This is where the problem is. If the difference at first is equal to k then it will not check again. I want it to check as long as the loop runs*/
}else{
is_jolly = false;
}
k--;
}
/*if is_jolly is true will print "Jolly" else "Not jolly"*/
}
}
return 0;
}
输入是
1 2000
5 1 4 2 -1 6
2 1999 1998
4 1 4 2 3
4 1 3 2 -2 <---- Here I am getting Jolly instead of Not Jolly
4 1 4 3 5
4 1 2 5 7
3 4 1 3
4 1 4 2 3
4 1 2 3 6 <--- Here I am getting Jolly instead of Not Jolly
2 1 3
1 1
其他一切都按预期工作。
像这样改变这个循环。
如果在任何时候,任何差异 [i]都不等于k,那么它就不是 jolly。否则,它是快乐的。因此,我们将在任何时候检查差异 [i]是否不等于 k 则is_jolly是false。
is_jolly = true; // suppose the answer is true
for(int i = 0; i < differences.size(); i++){
if(differences[i] != k){ // if at any time this value is not k then answer is false.
is_jolly = false;
break;
}
k--;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句