POJ 1700 Crossing River 贪心策略

来源:互联网 发布:udp socket编程 编辑:程序博客网 时间:2024/05/16 10:54

这个题比较有意思,小的时候就做过这种智力题....

首先分情况讨论(剩余人数记为left)

left==1时,直接自己过去

left==2时,直接一趟过去

left==3时,先用最快的人送走最慢的人,再回来,然后一趟就过去了

left>=4时,就有两种可能了(四个人为1,2,3,4)

                ① 1和4先过去,1回来,1和3再过去,1回来

                ② 1和2先过去,1回来,3和4再过去,2回来

                 挑其中最小耗费,这样就可以把3和4送过去了。

然后不断这么做直到left==0就可以了。

#include<stdio.h>#include<stdlib.h>#include<algorithm>using namespace std; int n,sp[1010];int greedy(){int left=n,sum=0;while(left>3){if(sp[left]+sp[1]+sp[2]*2<2*sp[1]+sp[left-1]+sp[left])sum+=sp[left]+sp[1]+sp[2]*2;elsesum+=2*sp[1]+sp[left-1]+sp[left];left-=2;}if(left==3){sum+=sp[3]+sp[2]+sp[1];}else if(left==2){sum+=sp[2];}else if(left==1){sum+=sp[1];}return sum;}int main(){int t,T,i;scanf("%d",&T);for(t=1;t<=T;t++){scanf("%d",&n);for(i=1;i<=n;i++)scanf("%d",&sp[i]);sort(sp+1,sp+n+1);printf("%d\n",greedy());}}


 

原创粉丝点击