1. 程式人生 > >poj - 1700 題解

poj - 1700 題解

貪心策略 排序 out += 還要 stream 每次 cin str

大概題意:N個人要過河,一個船最多承載兩人,且過河速度等於船上劃船速度最慢的人的速度,求過河的最短時間。

題目解法:首先對題目進行分析,可以發現:船過了河還要有一個人再把船送回來。

假設把人按過河速度從大到小排序並編號1-4,則會發現有兩種過河方式:1.13一組,1回來,24一組,2回來,12一組,完成;2.12一組,1回來,13一組,1回來,14一組,完成。

因此貪心策略就是:把人按過河速度從大到小排序,然後按上述方式過河,每次選取最優方式。

代碼如下:

 1     #include<iostream>
 2     #include<algorithm>
 3     using
namespace std; 4 int a[1001]; 5 bool com(const int& x,const int& y) 6 { 7 return x<y; 8 } 9 int main() 10 { 11 int T; 12 cin>>T; 13 for(int t=1;t<=T;t++) 14 { 15 int n; 16 cin>>n; 17
for(int i=1;i<=n;i++) 18 { 19 cin>>a[i]; 20 } 21 sort(a+1,a+n+1,com); 22 if(n==1) 23 { 24 cout<<a[1]<<endl; 25 continue; 26 } 27 if(n==2
) 28 { 29 cout<<a[2]<<endl; 30 continue; 31 } 32 if(n==3) 33 { 34 cout<<a[2]+a[1]+a[3]<<endl; 35 continue; 36 } 37 int res=a[2]; 38 int tip=n; 39 if(n%2==0) 40 { 41 while(tip>=4) 42 { 43 int t1=a[1]+a[2]+a[2]+a[tip]; 44 int t2=a[tip]+a[1]+a[tip-1]+a[1]; 45 res+=min(t1,t2); 46 tip-=2; 47 } 48 } 49 else 50 { 51 while(tip>=5) 52 { 53 int t1=a[1]+a[2]+a[2]+a[tip]; 54 int t2=a[1]+a[tip]+a[1]+a[tip-1]; 55 res+=min(t1,t2); 56 tip-=2; 57 } 58 res+=a[1]+a[3]; 59 } 60 cout<<res<<endl; 61 } 62 return 0; 63 }

poj - 1700 題解