dp HDU - 5074
按题意推表达式
#include<cstdio> #include<cstring> #define max(a, b) (a)>(b)?(a):(b) int dp[105][105], num[105][105], a[105]; int main() { int t; scanf("%d", &t); while (t--) { int n, m; scanf("%d%d", &n, &m); for (int i = 1; i <= m;++i) for (int j = 1; j <= m; ++j) scanf("%d", &num[i][j]); for (int i = 1; i <= n; ++i)scanf("%d", &a[i]); for (int i = 2; i <= n; ++i) { if (a[i - 1] > 0 && a[i] > 0)dp[i][a[i]] = dp[i - 1][a[i - 1]] + num[a[i - 1]][a[i]]; else if (a[i - 1]<0 && a[i]>0) { for (int k = 1; k <= m; ++k) dp[i][a[i]] = max(dp[i][a[i]], dp[i - 1][k] + num[k][a[i]]); } else if (a[i - 1] > 0 && a[i] < 0) { for (int k = 1; k <= m; ++k) dp[i][k] = max(dp[i][k], dp[i - 1][a[i - 1]] + num[a[i - 1]][k]); } else { for (int k = 1; k <= m;++k) for (int j = 1; j <= m; ++j) dp[i][k] = max(dp[i][k], dp[i - 1][j] + num[j][k]); } } int ans = 0; for (int i = 1; i <= m; ++i) ans = max(ans, dp[n][i]); printf("%d\n", ans);