-3
這是我對問題Codeforces-D2A-129 Cookies的解決方案。該程序輸出在測試用例11錯誤答案,這是:錯誤的答案雖然整個程序邏輯似乎正在工作
43 44 96 33 23 42 33 66 53 87 8 90 43 91 40 88 51 18 48 62 59 10 22 20 54 6 13 63 2 56 31 52 98 42 54 32 26 77 9 24 33 91 16 30 39 34 78 82 73 90 12 15 67 76 30 18 44 86 84 98 65 54 100 79 28 34 40 56 11 43 72 35 86 59 89 40 30 33 7月19日44 15
我的程序:
#include <cstdio>
#include <algorithm> // for count() and sort()
#include <vector>
using namespace std;
// function prototype
void erase_duplicates(vector<int> &, int, int);
int main()
{
int num; // number of bags of cookies
int total = 0; // total number of cookies
int ways = 0; // number of ways Olga can take a bag of cookies
int duplicates = 0; // number of duplicates of an element
scanf("%i", &num); // getting number of bags of cookies
vector<int> cookies(num); // number of cookies in the ith bag
// getting number of cookies in each bag
for(int i = 0; i < num; i++)
scanf("%i", &cookies[i]);
for(int j = 0; j < num; j++) // calculating total number of cookies
total += cookies[j];
// sorting the input
sort(cookies.begin(), cookies.end());
for(int k = 0; k < cookies.size(); k++)
{
if((total - cookies[k]) % 2 == 0)
{
// adding number of duplicates of the current element to the number of ways
duplicates = count(cookies.begin(), cookies.end(), cookies[k]);
ways += duplicates;
// erasing the duplicates of that element
erase_duplicates(cookies, cookies[k], k);
}
}
//printing the possible number of ways
printf("%i", ways);
return 0;
}
// This function erases the duplicates of the element passed as the second argument.
// Parameters are: vector of integers, element, index of the element.
void erase_duplicates(vector<int> &cookies, int value, int k){
for(int i = k; i < cookies.size(); i++){
if(cookies[i] == value) // if it is a duplicate, remove it.
cookies.erase(cookies.begin() + i);
}
}
這有什麼錯我的代碼?
*什麼是錯我的代碼* - 爲什麼不呢?調試代碼?調試是整個程序編寫過程的一部分。此外,要清除重複項,您可以簡單地使用'std :: unique' – PaulMcKenzie
這聽起來像您可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver
好的,謝謝。學過的知識。 –