Paired Up
时间限制: 1 Sec 内存限制: 128 MB题目描述
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 M cows (M≤1,000,000,000, M even) and partition them into M/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/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 A and B are paired up, then it takes a total of A+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.
输入
输出
样例输入
3
1 8
2 5
1 2
样例输出
10
题目简述
有M头牛,M是偶数,John要把他们分成M/2对牛。每对牛产奶的时间为两头牛产奶时间的总和,让M/2对奶牛同时开始产奶,设计一个让它们最快产完奶的配对方法,求最短的时间。输入,有N行,每行两个整数,x和y,表示有x头牛产奶用y时间。输出,最短的时间。
分析
要让所有配对的牛所用时间尽可能少,可以想到先给他们排序,让第一头牛和第M头牛配对,第二头牛和第M-1头牛配对……这样就可以让他们每对牛都产奶完的时间变小。但是实现起来并不容易,M的规模很大,我用数组提交是运行错误,所以可以选个更合适的数据结构。因为每次输入的是两个数可以想到用pair来存储数据。
参考代码
#include <iostream> #include <algorithm> #include <cstdio> using namespace std; pair<int,int> p[100100]; int main() { int N; int ans=0; int t; scanf("%d",&N); for(int i=1;i<=N;i++){ scanf("%d%d",&p[i].second,&p[i].first); } sort(p+1,p+N+1); int tou=1,wei=N; //跳出循环的条件不好判断可以自己举几个例子试试 while(wei>tou){ ans=max(ans,p[tou].first+p[wei].first); t=min(p[tou].second,p[wei].second); //重的可以直接减去 p[tou].second-=t; if(p[tou].second==0){ tou++; } p[wei].second-=t; if(p[wei].second==0){ wei--; } } if(wei==tou) ans=max(ans,p[tou].first+p[wei].first); printf("%d ",ans); return 0; }