链接:https://ac.nowcoder.com/acm/contest/5795/B来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
题目描述
On Derrick’s birthday, Derrick received a gift from his girlfriend Sandy. The gift consists n tiny balls, and each of them has two characteristics a and b. As Derrick is boring, he just wants to play with these balls.
Each time Derrick chooses two balls randomly. For each pair of balls x, y, Derrick defines their beautiful value as min(xa+yb,xb+ya).
Given the properties a and b of all the n tiny balls, Derrick will select exactly two of them and maximum their beautiful value. Now he needs your help, please help him.
输入描述:
Each input file only contains one test case.
The first line contains an integer n(1≤n≤2×105), indicating the total number of the tiny balls.
The second line contains nintegers a1,a2,…,an (1≤ai≤109), indicating the characteristic a of each ball.
The third line contains nintegers b1,b)2,…,bn (1≤bi≤109), indicating the characteristic b of each ball.
输出描述:
For each test case, output a single integer in a line indicating the maximum beautiful value of the given tiny balls.
实例输入
5
1 3 5 4 2
2 4 3 5 3
输出
8
大意:
n个球,每个球上两个数x,y.寻找两个球a,b.使得min(a.x+b.y, a.y+b.x)
最大,输出这个最大值。
分析:
起初想法,暴力,遍历第一个球,遍历第二个球。看了看数据范围,很明显,超时。
我们发现,有两个条件,a.x+b.y, a.y+b.x,取这两个较小的那个
,那是否可以先排一下序,使得:任意两个球 a, b (a < b) 的 a.y+b.x
都是 a.x+b.y
, a.y+b.x
中较大的一个(因为最后的结果和较大的那个无关),那么就只需要寻找 a.x+b.y
的最大值就可以了。
思路:先将数组特殊排序,之后一次遍历,找出最大的 a.x,最大的 b.y,相加即可。注意 a<b。
#include<bits/stdc++.h>
using namespace std;
int n;
struct T{
long long x,y;
}a[200010];
int cmp(T a,T b) //指定排序;
{
return a.y+b.x>=a.x+b.y; //使得任意两个球的a.y+b.x都是 a.x+b.y , a.y+b.x 中较大的一个;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i].x;
for(int i=1;i<=n;i++) cin>>a[i].y;
sort(a+1,a+1+n,cmp);
long long ans=0,maxa=a[1].x;
for(int i=2;i<=n;i++) //直接找最大的a.x和最大的b.y相加;
{
ans=max(ans,maxa+a[i].y);
maxa=max(maxa,a[i].x);
}
cout<<ans;
return 0;
}