洛谷 P3669 [USACO17OPEN]Paired Up 牛牛配对
题目描述
Farmer John finds that his cows are each easier to milk when they have another cow nearby for moral support. He therefore wants to take his MM cows (M \leq 1,000,000,000M≤1,000,000,000, MM even) and partition them into M/2M/2 pairs. Each pair of cows will then be ushered off to a separate stall in the barn for milking. The milking in each of these M/2M/2 stalls will take place simultaneously.
To make matters a bit complicated, each of Farmer John's cows has a different milk output. If cows of milk outputs AA and BBare paired up, then it takes a total of A+BA+B units of time to milk them both.
Please help Farmer John determine the minimum possible amount of time the entire milking process will take to complete, assuming he pairs the cows up in the best possible way.
有M(M为奇数)头奶牛,每头奶牛有一个产奶量,将这些奶牛两两配对,每对奶牛的产奶的时间为两头奶牛产奶量的总和。现在这M/2对奶牛同时产奶,问所需的最短时间是多少
输入输出格式
输入格式:
The first line of input contains NN (1 \leq N \leq 100,0001≤N≤100,000).
Each of the next NN lines contains two integers xx and yy, indicating that FJ has xx cows each with milk output yy (1 \leq y \leq 1,000,000,0001≤y≤1,000,000,000). The sum of the xx's is MM, the total number of cows.
第一行为一个正整数N
接下来有M行,每行两个正整数x和y,表示有x头奶牛的产奶量为y。保证所有x的总和等于M
输出格式:
Print out the minimum amount of time it takes FJ's cows to be milked, assuming they are optimally paired up.
输出产奶时间的最小值
输入输出样例
说明
Here, if the cows with outputs 8+2 are paired up, and those with outputs 5+5 are
paired up, the both stalls take 10 units of time for milking. Since milking
takes place simultaneously, the entire process would therefore complete after 10
units of time. Any other pairing would be sub-optimal, resulting in a stall taking more than 10
units of time to milk.
奶牛的产奶量分别为8,5,5,2。
让8和2配对,5和5配对,则产奶时间分别为10,10,所以这两对奶牛同时产奶的时间为10.
感谢 @ x咫尺天涯x 的翻译
思路:模拟+贪心。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int n,ans; struct nond{ int x,y; }v[100005]; int cmp(nond a,nond b){ return a.y<b.y; } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d%d",&v[i].x,&v[i].y); sort(v+1,v+1+n,cmp); int i=1,j=n; while(i<=j){ if(v[i].y+v[j].y>ans) ans=v[i].y+v[j].y; if(v[i].x>v[j].x){ v[i].x-=v[j].x;j--; } else if(v[i].x<v[j].x){ v[j].x-=v[i].x;i++; } else{ i++;j--; } } printf("%d",ans); }