Inputios
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. ui
Input contains multiple test cases. Process to the end of file.this
Outputspa
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. code
Sample Input
4
1
2
5
10orm
Sample Output
17
1 2
1
5 10
2
1 2
blog
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstdio> 4 #include <vector> 5 #include <algorithm> 6 #include <cstring> 7 #include <map> 8 using namespace std; 9 const int N=1009; 10 int s[N]; 11 int n; 12 13 int main() 14 { 15 int time=0; 16 int count=0; 17 int j; 18 while(scanf("%d",&n)!=EOF) 19 { 20 time=0; 21 count =0; 22 23 for(int i=0;i<n;i++) 24 { 25 scanf("%d",&s[i]); 26 } 27 sort(s,s+n); 28 j=n-1;//最慢的人 29 while(count<=n-4)//4我的的狀況 30 { 31 if(2*s[1]<s[0]+s[j-1]) 32 { 33 time+=s[1]+s[1]+s[j]+s[0]; 34 } 35 else 36 { 37 time+=s[j]+s[0]+s[0]+s[j-1]; 38 } 39 count+=2;//有2我的過橋 40 j-=2;//規模減小2 41 }
//剩下的3種狀況 42 switch(n-count) 43 { 44 case 1: 45 time+=s[0]; 46 break; 47 case 2: 48 time+=s[1]; 49 break; 50 case 3: 51 time+=s[0]+s[1]+s[2]; 52 break; 53 } 54 printf("%d\n",time);//輸出總時間 55 j=n-1; 56 count =0;
//輸出過橋的方法 57 while(count<=n-4) 58 { 59 if(2*s[1]<s[0]+s[j-1]) 60 { 61 printf("%d %d\n%d\n",s[0],s[1],s[0]); 62 printf("%d %d\n%d\n",s[j-1],s[j],s[1]); 63 } 64 else 65 { 66 printf("%d %d\n%d\n",s[0],s[j-1],s[0]); 67 printf("%d %d\n%d\n",s[0],s[j],s[0]); 68 } 69 count+=2; 70 j-=2; 71 72 } 73 switch(n-count) 74 { 75 case 1: 76 printf("%d\n",s[0]); 77 break; 78 case 2: 79 printf("%d %d\n",s[0],s[1]); 80 break; 81 case 3: 82 printf("%d %d\n%d\n",s[0],s[1],s[0]); 83 printf("%d %d\n",s[0],s[2]); 84 break; 85 } 86 } 87 return 0; 88 }