标签:style class blog c code tar
原题:
http://acm.timus.ru/problem.aspx?space=1&num=1826
1826. Minefield Time limit: 0.5 second Memory limit: 64 MB To fulfill an assignment, a reconnaissance group of n people must cross the enemy‘s minefield. Since the group has only one mine detector, the following course of action is taken: two agents cross the field to the enemy‘s side and then one agent brings the mine detector back to the remaining group. This is repeated until only two agents remain. These two agents then cross the field together. Each person gets across the field at their own speed. The speed of a pair is determined by the speed of its slower member. Find the minimal time the whole group needs to get over the minefield. Input The first line contains the integer n (2 ≤ n ≤ 100). The i-th of the following n lines specifies the time the i-th member of the group needs to get over the minefield (the time is an integer from 1 to 600). Output Output the minimal total time the group needs to cross the minefield. |
2~100个人要过雷区,只有一个探雷器,一次最多只能2个人过去,所以过去的流程是:过去2个回来一个过去2个回来一个…直到只剩2个的时候一起过去。2个一起走的时候以速度慢的人的速度为准。样例我看了好久没看懂,样例是4个人,单独过去的时间分别为1,2,5,10,先是1和2过去,1回来,5和10过去,2回来,1和2过去,一共2+1+10+2+2=17。
大致有两种策略,一种是最小的那个带大的过去,再回来带第二大的过去,再回来;另一种是最小的两个过去,最小的回来,然后最大的两个过去,第二小的回来。
好像可以贪心,这两种策略结束时都是最小的两个还在这边,最大的两个都去了那边,状态是一样的,所以这里选最优的策略就好。
不过我做的时候没想通,用了动规,i从大到小,dp[i][0]记录把i送过去时第二小的还在自己这边所耗的总时间,dp[i][1]记录把i送过去时第二小的在对面,所用的总时间。这样记录了第二小的位置,比较方便讨论几种送法。
动规代码如下:
1 #include<iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include<vector> 6 #include<algorithm> 7 #include<cstring> 8 #define MAXN 111 9 #define RE freopen("in.txt","r",stdin); 10 #define inf 6666666 11 using namespace std; 12 13 int n; 14 int a[MAXN]; 15 int dp[MAXN][2]; 16 17 int farm(); 18 void init(); 19 20 int main() 21 { 22 //RE 23 while(scanf("%d",&n)!=EOF) 24 { 25 farm(); 26 } 27 return 0; 28 } 29 30 int farm() 31 { 32 int i,ans; 33 for(i=0;i<n;i++) 34 { 35 scanf("%d",&a[i]); 36 } 37 sort(a,a+n); 38 memset(dp,-1,sizeof(dp)); 39 for(i=0;i<=n+1;i++) 40 { 41 dp[i][0]=inf; 42 dp[i][1]=inf; 43 } 44 dp[n][0]=0; 45 dp[n][1]=a[1]+a[0]; 46 for(i=n-1;i>1;i--) 47 { 48 dp[i][0]=dp[i+1][0]+a[i]+a[0]; 49 if(i<n-1) dp[i][0]=min(dp[i][0],dp[i+2][1]+a[i+1]+a[1]); 50 dp[i][1]=dp[i+1][1]+a[i]+a[0]; 51 dp[i][1]=min(dp[i][1],dp[i][0]+a[1]+a[0]); 52 } 53 ans=min(dp[2][0]+a[1],dp[3][1]+a[2]); 54 printf("%d\n",ans); 55 return 0; 56 } 57 58 59 void init() 60 { 61 62 }
贪心的我没写…应该比这个简单。
URAL1826. Minefield 题解,布布扣,bubuko.com
标签:style class blog c code tar
原文地址:http://www.cnblogs.com/yuiffy/p/3748128.html