• CodeForce-808C Tea Party(结构体排序贪心)


    Tea Party

    CodeForces - 808C

    现在有 n 个杯子,每个杯子的容量为 a1, a2, ..., an。他现在一共有 w 毫升茶 (w ≤ a1 + a2 + ... + an)。现在要求每个杯子都满足以下条件:

    • 每个杯子必须装整数的茶水
    • 每个杯子至少装一半的茶水(奇数向上取整)
    • 所有茶水必须放到杯子中
    • 容量大的杯子里的水不可以比容量小的杯子里的茶水少

    给出任意一组合法答案。如果不存在合法方案,输出 -1。

    解法:

    贪心,先把所有的杯子都放好一半(如果w<(a1 + a2 + ... + an)/2,说明不存在合法方案),如果还有剩余的茶,都往最大的大杯子里倒,倒满了就往第二大的杯子里倒,以此类推。
    所以要先根据杯子容量把所有杯子排序一遍,把茶都分配倒完之后,再根据杯子原本的序号排好序,从1~n输出结果。

    #include <cstdio>
    #include <iostream>
    #include <cmath>
    #include <algorithm>
    #include <string>
    #include <cstring>
    using namespace std;
    #define _ ios::sync_with_stdio(false),cin.tie(0)
    
    const int MAXN = 5010;
    const int INF = 0xfffffff;
    typedef long long ll;
    
    struct node
    {
        int a;
        int b;
        int id;
    }cup[150];
    
    bool cmp1(node a,node b)
    {
        return a.a>b.a;
    }
    bool cmp2(node a,node b)
    {
        return a.id<b.id;
    }
    int main()
    {
       int n,w;
       int half=0;
       cin>>n>>w;
       for(int i=0;i<n;i++)
       {
           int x;
           cin>>x;
           cup[i].a=x;
           cup[i].b=(cup[i].a+1)/2;
           cup[i].id=i;
           half+=cup[i].b;
       }
       if(w<half)
       {
           cout<<-1<<endl;
           return 0;
       }
       w-=half;
       int i=0;
       sort(cup,cup+n,cmp1);
    //    cout<<w<<endl;
       while(w>0)
       {
           if(w>=cup[i].a-cup[i].b)
           {
               w-=cup[i].a-cup[i].b;
               cup[i].b=cup[i].a;
           }
           else 
           {
               cup[i].b+=w;
            //    cout<<"i="<<i<<" cup[i].b="<<cup[i].b<<endl;
               w=0;
           }
           i++;
       }
       sort(cup,cup+n,cmp2);
       for(int j=0;j<n;j++)
            cout<<cup[j].b<<" ";
       return 0;
    }
  • 相关阅读:
    软件工程第1次阅读作业
    软件工程第0次作业
    OO第四次博客
    OO第三次总结
    OO第二次总结
    OO第一次总结
    提问回顾与个人总结
    结对项目:最长单词链
    第一次阅读作业
    第四次博客
  • 原文地址:https://www.cnblogs.com/YingZhixin/p/7126981.html
Copyright © 2020-2023  润新知