【pair的运用】Paired Up(USACO)

 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 (M1,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.

输入

The first line of input contains N (1N100,000). Each of the next N lines contains two integers x and y, indicating that FJ has x cows each with milk output y (1y1,000,000,000). The sum of the x's is M, the total number of cows.

输出

Print out the minimum amount of time it takes FJ's cows to be milked, assuming they are optimally paired up.

样例输入

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;
}
祝你早日攒够失望,然后开始新的生活。
原文地址:https://www.cnblogs.com/LuRenJiang/p/7256320.html