需要帮助避免SPOJ上的“错误答案”

时间:2013-09-07 13:00:54

标签: c++ algorithm

问题:http://www.spoj.com/problems/EGYPIZZA/

我一直试图解决这个'PIZZA'问题很长一段时间,我尝试了很多很多 输入,它似乎在我的机器上工作正常,但在线判断一直拒绝接受mu代码说错误的答案! 请帮帮我... 这是我的代码:

 #include<iostream>
#include<cstring>
using namespace std;
int main()
{
    char str[4],b[3][4]= {"1/4","1/2","3/4"};
    unsigned int n, s = 1, count1 = 0, count2 = 0, count3 = 0;
    scanf("%u",&n);
    while(n--)
    {
        cin>>str;
        if(strcmp(str,b[0])==0)
            count2++;               
         else if(strcmp(str,b[1])==0)
             count1++;
         else if(strcmp(str,b[2])==0)
              count3++;
    }
    while(count3!=0 && count2!=0)
      {
               count2--; count3--; s++;
      }  
        if(count1%2!=0)
          if(count2/2!=0)
            {
                    count2-=2; count1--; s++;
            }   
            s = s + (count1/2) + (count1%2) + (count2/4) + (count2%4) + count3 ;
    printf("%u\n",s);
    return 0;
}

编辑:
我在你的建议后更新了我的代码,请检查出来的人! 还是给出了错误的答案..

2 个答案:

答案 0 :(得分:3)

接受的解决方案:

#include<iostream>

using namespace std;

int main()
{
    string s;
    int n, sum = 1, count1 = 0, count2 = 0, count3 = 0, extra;
    cin >> n;
    for (int i=0; i < n; i++)
    {
        cin >> s;
        if (s == "1/2")count1 ++;
        if (s == "1/4")count2 ++;
        if (s == "3/4")count3 ++;
    }

    sum += count3 + count1/2.0 + 0.5;
    extra = count3 + (count1%2)*2;
    if (count2 >= extra)
    {
       count2 -= extra;
       sum += count2 / 4.0 + 0.75;
    }

    cout << sum << endl;

    return 0;
}

如果aboTrika没有像其他人那样坚持把披萨作为一件,那么这个问题会更有趣。 :)

答案 1 :(得分:1)

您的程序存在许多问题,例如使用简单计数器就足够的向量,以及使用适合整数运算的浮点数。也许最严重的问题是声明s = s + q/4 + h/2,它实际上通过将四分之一比萨分组在一起并将半比萨分组在一起来满足大多数1/4披萨的要求。相反,应该首先使用1/4披萨的请求来补充尽可能多的3/4披萨请求,然后如果所请求的一半的奇数是奇数,则填充1/2披萨请求,然后才一起使用。