您的位置:首页 > 其它

哈理工oj 1079 I can do it【贪心】

2016-03-19 10:14 429 查看
I can do it
Time Limit: 1000 MSMemory Limit: 65536 K
Total Submit: 215(91 users)Total Accepted: 102(75 users)Rating: 





Special Judge: No
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 (can't be empty) , 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. (2 <= 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
1

3

1 100

2 100

3 1

Sample Output
Case 1: 3

题目大意:给你n个元素,给他们分成两个集合,这里我们命名为集合X,集合Y,使得我们在集合X里边找到最大的Ai,在集合Y里边找到最大的Bi,使得Ai+Bi尽可能的小,问如何分配才能得到这个最小值,并且输出这个最小值。

思路:将输入中的左边一列Ai排序,将输入种右边一列Bi也排序,我们找到拥有更大价值的一个组合,取其最小值、然后在另外一边找到最大值,加和就是最终贪心出来的结果。

简单证明:因为我们从两边找到各自的最大值,我们怎样也逃脱不了一方集合的最大值选取,也就是说最终结果里边一定有A【】里边的最大Ai或者B【】里边最大值Bi,那么我们为了更小的取值,我们只能避免加入max(A【max】,B【max】)这个元素,这样我们就达到了贪心的目的。

对应AC代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int x[100005];
int y[100005];
int main()
{
int kase=0;
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d%d",&x[i],&y[i]);
}
sort(x,x+n);
sort(y,y+n);
int pos=-1;
for(int i=n-1;i>=0;i--)
{
if(x[i]!=y[i])
{
pos=i;
break;
}
}
printf("Case %d: ",++kase);
if(x[pos]>y[pos])
{
int vala=x[0];
for(int i=n-1;i>=0;i--)
{
if(i!=pos)
{
vala+=y[i];
break;
}
}
printf("%d\n",vala);
}
else
{
int valb=y[0];
for(int i=n-1;i>=0;i--)
{
if(i!=pos)
{
valb+=x[i];
break;
}
}
printf("%d\n",valb);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息