NYOJ 716 River Crossing(动态规划)
River Crossing
時間限制:1000?ms ?|? 內存限制:65535?KB 難度:4描述
Afandi is herding?N?sheep?across the expanses of?grassland??when he finds himself blocked by a river. A single raft is available for transportation.
?
Afandi knows that he must ride on the raft for all crossings, but adding sheep to the raft makes it traverse the river more slowly.
?
When Afandi is on the raft alone, it can cross the river in M minutes When the i sheep are added, it takes Mi minutes longer to cross the river than with i-1 sheep (i.e., total M+M1 ??minutes with one sheep, M+M1+M2 with two, etc.).
?
Determine the minimum time it takes for Afandi to get all of the sheep across the river (including time returning to get more sheep).
輸入
* Line 1: one space-separated integers: N and M (1 ≤ N ≤ 1000 , 1≤ M ≤ 500).
* Lines 2..N+1: Line i+1 contains a single integer: Mi (1 ≤ Mi ≤ 1000)
輸出
這是去年省賽的一道題,當時寫的代碼交上去一直WA,和隊友討論了好長時間也沒找到哪里錯了。后來才知道我們的思想就是錯的。因為這個題是dp,但是我們一直當成貪心做的。比賽完就放下沒做,沒想到今天比賽又拉出來了,雖然知道是dp,但是由于沒有找到狀態轉移方程,導致今天又沒有做出來。好傷心。。。。
題意:有1個人和N只羊要過河。一個人單獨過河花費的時間是M,每次帶一只羊過河花費時間M+M1,帶兩只羊過河花費時間M+M1+M2……給出N、M和Mi,問N只羊全部過河最少花費的時間是多少。
分析:用一個前綴和數組time,time[i]表示單獨運送i只羊所花費的時間。dp[i]表示一個人和i只羊過河所花費的最短時間,則開始時dp[i] = time[i] + M,以后更新時,dp[i] = min(dp[i],dp[i-j] + m + dp[j]),j從1循環到i-1,即把i只羊分成兩個階段來運,只需求出這兩個階段的和,然后加上人從對岸回來所用的時間,與dp[i]進行比較,取最小值。
#include<stdio.h> #include<algorithm> using namespace std; int dp[1005], time[1005]; int main() {int T, n, m, i, j;scanf("%d",&T);while(T--){int a;scanf("%d%d",&n, &m);time[0] = 0;for(i = 1; i <= n; i++){scanf("%d",&a);time[i] = time[i-1] + a;}for(i = 1; i <= n; i++){dp[i] = time[i] + m;for(j = 1; j < i; j++)dp[i] = min(dp[i], dp[i-j] + dp[j] + m);}printf("%d\n",dp[n]);}return 0; } //time[i]表示一次運送i只羊所花費的時間 //dp[i]表示人和i只羊一起過河所花費的最短時間
總結
以上是生活随笔為你收集整理的NYOJ 716 River Crossing(动态规划)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【5折秒杀】戴尔轻薄商务本只卖2899元
- 下一篇: NYOJ 309 BOBSLEDDING