您的位置:首页 > 其它

HDOJ 3552 I can do it!(贪心)

2015-12-20 11:55 169 查看


I can do it!

Time Limit: 2000/2000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)

Total Submission(s): 983    Accepted Submission(s): 464


[align=left]Problem Description[/align]
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.
 

[align=left]Input[/align]
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)
 

[align=left]Output[/align]
For each test cases, output the minimum value.
 

[align=left]Sample Input[/align]

1
3
1 100
2 100
3 1

 

[align=left]Sample Output[/align]

Case 1: 3

 
题意:有n个元素,每个元素有两个内容,分别是整数ai和整数bi。把这n个元素分成两个集合A,B,求A集合中最大的ai加上B集合中最大的bi的最小值。

题解:在确立好A集合中最大的ai时,将小于等于ai的aj这些元素放在A集合中最合适,这样既不影响A集合中取出来的最大值,又不会增加B集合中的最大的bi值。这一点便是贪心思想。   先将元素按照ai的值从大到小排序,遍历这些元素,确立当前的A集合中最大的ai,将含有大于ai的aj这些元素放入B集合,并记录B集合中最大的bi值,不断更新最小的max(ai)+max(bi)即可。

代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
int a,b;
}num[100010];

int cmp(node x,node y)
{
return x.a>y.a;
}

int main()
{
int t,n,A,B,i,k=1;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=1;i<=n;++i)
scanf("%d%d",&num[i].a,&num[i].b);
sort(num+1,num+n+1,cmp);
int ans=0x3f3f3f3f;
num[n+1].a=0;//这么弄是考虑到A或者B集合为空的情况,不考虑也能AC
num[0].b=0;
B=0;
for(i=1;i<=n+1;++i)
{
B=max(B,num[i-1].b);
ans=min(ans,num[i].a+B);
}
printf("Case %d: %d\n",k++,ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: