错误的答案虽然整个程序逻辑似乎正在起作用

时间:2017-01-20 12:17:06

标签: c++

这是我对问题Codeforces-D2A-129 Cookies的解决方案。程序在测试用例11输出错误的答案,即:

82

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);
    }
}

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

实际上不需要排序。 问题可以解决为 - 首先对所有数组元素求和,找出偶数和奇数元素的数量。 接下来,如果数组元素的总和是奇数,则可以窃取具有奇数个cookie的行李,因此答案将是奇数元素的数量,如果总和是偶数则答案是具有偶数个cookie的行李数。

逻辑 - 两个奇数的差异是偶数         两个偶数的差异是偶数

#include<iostream>
#include<vector>

 using namespace std;
 int main()
{
    int n;
    vector<int> num;
    cin>>n;
    num.resize(n);
    int even=0,odd=0,sum=0;
    for(int i=0;i<n;i++)
    {
        cin>>num[i];
        sum+=num[i];
        if(num[i]%2)
         odd++;
        else even++;
    }
   if(sum%2)
      cout<<odd<<endl;
   else cout<<even<<endl;
    return 0; 
 }