标签:hdoj4540
2 2 1 10 4 9 3 5 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15
1 1
开始用深搜,结果超时,换成O(n^3)的DP竟然过了,看来时间复杂度分析还是不过关唉。
#include <stdio.h> #include <stdlib.h> #include <string.h> bool arr[21][502]; int dp[21][502]; int main(){ int n, k, t, minlen; while(scanf("%d%d", &n, &k) == 2){ memset(arr, 0, sizeof(arr)); memset(dp, 0, sizeof(dp)); for(int i = 1; i <= n; ++i) for(int j = 1; j <= k; ++j){ scanf("%d", &t); arr[i][t] = 1; } for(int i = 2; i <= n; ++i){ for(int j = 1; j <= 501; ++j){ if(i == 2 && arr[i][j]){ for(int k = 0; k < 501; ++k){ if(arr[i-1][k]){ if(dp[i][j] == 0) dp[i][j] = dp[i-1][k] + abs(k - j); else if(dp[i-1][k] + abs(k - j) < dp[i][j]) dp[i][j] = dp[i-1][k] + abs(k - j); } } continue; } if(arr[i][j]){ for(int k = 0; k < 501; ++k){ if(dp[i-1][k]){ if(dp[i][j] == 0) dp[i][j] = dp[i-1][k] + abs(k - j); else if(dp[i-1][k] + abs(k - j) < dp[i][j]) dp[i][j] = dp[i-1][k] + abs(k - j); } } } } } minlen = 0; for(int i = 1; i < 501; ++i) if(dp[n][i]){ if(!minlen) minlen = dp[n][i]; else if(dp[n][i] < minlen) minlen = dp[n][i]; } printf("%d\n", minlen); } return 0; }
HDOJ4540 威威猫系列故事——打地鼠 【DP】,布布扣,bubuko.com
标签:hdoj4540
原文地址:http://blog.csdn.net/chang_mu/article/details/25397263