cf23C Oranges and Apples(很好的贪心题)

地址:https://vjudge.net/problem/CodeForces-23C/origin

题意:

n

给出2*n-1个箱子,分别含有a个苹果,o个橘子

能否找出n个箱子,保证其可装的苹果不少于总苹果数一半,橘子不少于总橘子数一半。

解析:

经过分析,答案是一定存在的。

先按苹果数从小到大排序。

令第2*n-1个必拿。

假设2*n-1==7

a1,a2,a3,a4,a5,a6,a7

两两相比(苹果已经排好序,按橘子比较),a1和a2,a3和a4.......

那么这种拿法,一定能保证苹果>=suma/2。

假设拿了a1+a3+a6+a7,那么剩的是a2+a4+a5,前者一定大于后者,一定>=suma/2

不管怎么拿,只要保证两两拿一个,一定可以满足。

同理,对于橘子也是一样,两两取橘子数较大的那个,一定能保证>=sumo/2;

#include <bits/stdc++.h>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn =1e6+30;
struct node
{
    int a,o,id;
}st[maxn];
int n;
bool cmp(node a,node b)
{
    return a.a<b.a;
}
void solve()
{
    cin>>n;
    for(int i=1;i<=2*n-1;i++)
    {
        cin>>st[i].a>>st[i].o;
        st[i].id=i;
    }
    sort(st+1,st+1+2*n-1,cmp);
    cout<<"YES"<<endl;
    for(int i=2;i<=2*n-1;i+=2)
    {
        if(st[i].o>st[i-1].o)
        {
            cout<<st[i].id<<" ";
        }
        else
            cout<<st[i-1].id<<" ";
    }
    cout<<st[2*n-1].id<<endl;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        solve();
    }
    
}
原文地址:https://www.cnblogs.com/liyexin/p/13794939.html