hdu3552I can do it!(贪心)

来源:互联网 发布:上古卷轴5跳出优化补丁 编辑:程序博客网 时间:2024/05/17 02:55

I can do it!

Time Limit: 2000/2000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 1045    Accepted Submission(s): 484


Problem Description
Given n elements, which have two properties, say Property A and Property B. For convenience, we use two integers Ai and Bi to measure the two properties.
Your task is, to partition the element into two sets, say Set A and Set B , which minimizes the value of max(x∈Set A) {Ax}+max(y∈Set B) {By}.
See sample test cases for further details.
 

Input
There are multiple test cases, the first line of input contains an integer denoting the number of test cases.
For each test case, the first line contains an integer N, indicates the number of elements. (1 <= N <= 100000)
For the next N lines, every line contains two integers Ai and Bi indicate the Property A and Property B of the ith element. (0 <= Ai, Bi <= 1000000000)
 

Output
For each test cases, output the minimum value.
 

Sample Input
131 1002 1003 1
 

Sample Output
Case 1: 3
 解题思路:有N个物品,其都有两个属性a,b;如果将这N个物品分成两个集合A,B;求A,B两个集合中A集合中每个物品的a属性中的最大值与B集合中物品中b属性最大的值之和的最小值?允许其中一个集合为空。例如示例中若A={(1,100),(2,100),(3,1)},B=空集的话,这就能得到最新值3;
本题解题思路就是贪心,可以想一下,如果A集合中的最大值如果确定的话,那么所有属性a小于这个最大值都应该放到集合A中(因为它们既不会有比这个最大值更大,如果放入B集合的话还有可能是最后的值变大)剩下的就是B集合的元素;从中找出属性b最大与刚才的最大的a相加;循环n-1次,每次更换一个a,找出其中的最小值即可。
AC代码:
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;struct node{int a,b;}ans[100010];int cmp(node x,node y){return x.a>y.a;}int main(){int n,t;int i,j,k,x,y,ca=1;scanf("%d",&t);while(t--){scanf("%d",&n);for(i=0;i<n;i++){ scanf("%d%d",&ans[i].a,&ans[i].b); if(y<ans[i].b) y=ans[i].b;}sort(ans,ans+n,cmp);if(y<ans[0].a)   //此步是找出当A集合为空或B集合为空的两个值最小的那个 k=y;else k=ans[0].a;y=0;for(i=1;i<n;i++){  x=ans[i].a;            //以ans[i].a作为当前A集合a属性的最大值;  y=max(y,ans[i-1].b);  //找出B集合的b属性最大值;  k=min(k,x+y);         //选出最小的值}printf("Case %d: %d\n",ca++,k);}return 0;}



0 0
原创粉丝点击