P3669 [USACO17OPEN]Paired Up S

https://www.luogu.com.cn/problem/P3669
涉及知识点:贪心
橙色题
 
思路:
每次选产奶量最少的和产奶量最多的配对,取它们产奶时间的最大值
代码:
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=100005;
struct Node
{
    int x, y;
}a[N];
bool cmp(Node s, Node t) //按照产奶量从大到小排序
{
    return s.y<t.y;
}
int n,ans;
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d%d",&a[i].x,&a[i].y);
    sort(a+1,a+1+n,cmp);
    int i=1,j=n; //头尾指针分别指向产奶量最少的和产奶量最多的
    while(i<=j)
    {
        if(a[i].y+a[j].y>ans) ans=a[i].y+a[j].y; //产奶时间当前最长,更新答案ans
        if(a[i].x>a[j].x) //产奶少的奶牛数量大于产奶多的
        {
            a[i].x-=a[j].x; //产奶少的奶牛数量减去与产奶多的奶牛配对的数量
            j--; //修改尾指针
        } //下面同上不解释
        else if(a[i].x<a[j].x)
        {
            a[j].x-=a[i].x;
            i++;
        }
        else //产奶一样多,同时修改头尾指针
        {
            i++;
            j--;
        }
    }
    printf("%d",ans); //最后输出ans即可
}
 

 

posted @ 2022-07-16 21:05  -イレイナ  阅读(53)  评论(0)    收藏  举报