I can do it | ||||||
| ||||||
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. | ||||||
Input | ||||||
There are multiple test cases, the first line of input contains an integer denoting the number of test cases. | ||||||
Output | ||||||
For each test cases, output the minimum value. | ||||||
Sample Input | ||||||
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);
}
}
}