TOJ-1353 Bridge

n people wish to cross a bridge at night. A group of at most two people may cross at any time, and each group must have a flashlight. Only one flashlight is available among the n people, so some sort of shuttle arrangement must be arranged in order to return the flashlight so that more people may cross.

Each person has a different crossing speed; the speed of a group is determined by the speed of the slower member. Your job is to determine a strategy that gets all n people across the bridge in the minimum time.

The first line of input contains n, followed by n lines giving the crossing times for each of the people. There are not more than 1000 people and nobody takes more than 100 seconds to cross the bridge.

The first line of output must contain the total number of seconds required for all n people to cross the bridge. The following lines give a strategy for achieving this time. Each line contains either one or two integers, indicating which person or people form the next group to cross. (Each person is indicated by the crossing time specified in the input. Although many people may have the same crossing time the ambiguity is of no consequence.) Note that the crossings alternate directions, as it is necessary to return the flashlight so that more may cross. If more than one strategy yields the minimal time, any one will do.

Sample Input

4
1
2
5
10

Possible Output for Sample Input

17
1 2
1
5 10
2
1 2

Note: Special judge problem, you may get "Wrong Answer" when output in wrong format.



Source: Waterloo Local Contest Sep. 30, 2000

 

样例已经给了很好的提示,当人数超过3人时,有两种可能的最优情况:

最快两人ab,最慢两人cd

情况1:

  a b  a  c d  b

情况2:

  a c  a  a d  a

两种取其更优者。

#include<stdio.h>
#include <math.h>
#include <algorithm>
using namespace std; 
int n,p[1010];
int cmp(const void *a, const void *b)  
{  
    return *(int *)a - *(int *)b;  
}
int main(){
    int i,j,sum;
    while(~scanf("%d",&n)){
        for(i=0;i<n;i++){
            scanf("%d",&p[i]);
        }
        qsort(p,n,sizeof(int),cmp);
        if(n==1){
            printf("%d\n%d\n", p[0], p[0]);
        }
        else if(n==2){
            printf("%d\n%d %d\n", p[1], p[0], p[1]); 
        }
        else{
            sum = p[1];//最后必然p0,p1一起过,先加上 
            for(i=n-2;i>=2;i-=2){
                sum += min(p[0]*2+p[i]+p[i+1],p[i+1]+p[1]*2+p[0]);
            }
            if(n%2==1)    sum += p[0]+p[2];
            printf("%d\n",sum);
            for(i=n-2;i>=2;i-=2){
                if(p[0]*2+p[i]+p[i+1]>p[i+1]+p[1]*2+p[0]){
                    printf("%d %d\n%d\n%d %d\n%d\n",p[0],p[1],p[0],p[i],p[i+1],p[1]);
                }
                else{
                    printf("%d %d\n%d\n%d %d\n%d\n",p[0],p[i+1],p[0],p[0],p[i],p[0]);
                }
                
            }
            if(n%2==1)    printf("%d %d\n%d\n",p[0],p[2],p[0]);
            printf("%d %d\n",p[0],p[1]);
        }
    }
    return 0;
}

 

 

posted @ 2017-02-12 14:18  DGSX  阅读(237)  评论(0编辑  收藏  举报