bzoj 1820 dp
最普通dp要4维,因为肯定有一个在上一个的位置,所以可以变为3维,然后滚动数组优化一下。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define PII pair<int, int> #define PLI pair<LL, int> #define ull unsigned long long using namespace std; const int N = 1000 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; int n, m, cur, a[207][207], b[1007]; LL dp[2][207][207]; int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) scanf("%d", &a[i][j]); b[0] = 1; while(scanf("%d", &b[++m]) != EOF){} memset(dp[cur], INF, sizeof(dp[cur])); dp[cur][2][3] = dp[cur][3][2] = 0; LL ans = INF; for(int i = 1; i <= m; i++) { cur ^= 1; memset(dp[cur], INF, sizeof(dp[cur])); for(int j = 1; j <= n; j++) { for(int k = 1; k <= n; k++) { dp[cur][j][k] = min(dp[cur][j][k], dp[cur^1][j][k] + a[b[i-1]][b[i]]); dp[cur][b[i-1]][k] = min(dp[cur][b[i-1]][k], dp[cur^1][j][k] + a[j][b[i]]); dp[cur][j][b[i-1]] = min(dp[cur][j][b[i-1]], dp[cur^1][j][k] + a[k][b[i]]); } } } for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) ans = min(ans, dp[cur][i][j]); printf("%lld\n", ans); return 0; } /* */