题目链接:https://www.acwing.com/problem/content/276/
以已经处理完的请求为阶段,设 (dp[i][j][k]) 表示已经处理完前 (i) 个请求,服务员分别在 (p[i], j, k) 处的最小花费
刷表法转移即可
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxn = 1010;
int L, n;
int p[maxn], c[maxn][maxn], f[maxn][210][210];
ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }
int main(){
L = read(), n = read();
for(int i = 1 ; i <= L ; ++i){
for(int j = 1 ; j <= L ; ++j){
c[i][j] = read();
}
}
p[0] = 3;
for(int i = 1 ; i <= n ; ++i){
p[i] = read();
}
memset(f, 0x3f, sizeof(f));
f[0][1][2] = 0;
for(int i = 0 ; i < n ; ++i){
for(int j = 1 ; j <= L ; ++j){
for(int k = 1 ; k <= L ; ++k){
if(j == k || j == p[i] || k == p[i]) continue;
f[i + 1][j][k] = min(f[i + 1][j][k], f[i][j][k] + c[p[i]][p[i + 1]]);
f[i + 1][p[i]][k] = min(f[i + 1][p[i]][k], f[i][j][k] + c[j][p[i + 1]]);
f[i + 1][j][p[i]] = min(f[i + 1][j][p[i]], f[i][j][k] + c[k][p[i + 1]]);
}
}
}
int ans = 1000000007;
for(int i = 1 ; i <= L ; ++i){
for(int j = 1 ; j <= L ; ++j){
ans = min(ans, f[n][i][j]);
}
}
printf("%d
", ans);
return 0;
}