感觉这题上了些难度了。。第一次做三维DP。。。昨晚看完后睡了10个小时后想出来了。。。睡眠果然是精力集中的保障啊。。。还有这题倒着推很好写
状态转移方程:
dp[i][j][k]=min(dp[i+1][j][k]+map[i][i+1],dp[i+1][i][k]+map[j][i+1],dp[i+1][i][j]+map[k][i+1]);
//为避免混淆。。。数组还是从1开始搞起吧。。。 #include<stdio.h> #include<string.h> #define inf 100000000 int ncase; int n; int map[35][35]; int dp[35][35][35]; int min(int a, int b, int c) { return (a<=b)?((a<=c)? a:c):((b<=c)? b:c); } int main() { scanf("%d",&ncase); while (ncase--) { memset(dp, 0, sizeof(dp)); scanf("%d",&n); for (int i=0; i<=n; i++) for (int j=0; j<=n; j++) map[i][j]=inf; for (int i=1; i<=n-1; i++) for (int j=i+1; j<=n; j++) scanf("%d",map[i]+j); for (int i=n-1; i>=1; i--) { for (int j=1; j<=i; j++) { for (int k=1; k<=j; k++) { dp[i][j][k]=min(dp[i+1][j][k]+map[i][i+1],dp[i+1][i][k]+map[j][i+1],dp[i+1][i][j]+map[k][i+1]); } } } printf("%d\n",dp[1][1][1]); } }
啊