题意:给n点的无相连通图, 以及一个序列a, 要修改序列中的数,使得经过最少次数修改之后序列中的每两个相邻的数在图中相邻或者相等。
思路:设dp[i][j]第i个数为j的时候最少的修改次数, 则dp[i][j] = min {dp[i - 1][k] + t | k和j相等或在图中相邻 }(其中j =a[i]时t=0,否则t为1)
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
const int INF = 1e9;
const int maxn = 110;
using namespace std;
int a[maxn * 2], T, n, m;
int dp[maxn * 2][maxn], L;
vector<int> G[maxn];
int main() {
scanf("%d", &T);
while(T--) {
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++) {
G[i].clear();
G[i].push_back(i);
}
while(m--) {
int u, v;
scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
scanf("%d", &L);
for(int i = 1; i <= L; i++) {
scanf("%d", &a[i]);
for(int j = 0; j <= n; j++) dp[i][j] = INF;
}
for(int j = 0; j <= n; j++) dp[0][j] = 0;
for(int i = 1; i <= L; i++) {
for(int v = 1; v <= n; v++) {
int t = v == a[i] ? 0 : 1;
for(int j = 0; j < G[v].size(); j++) {
int o = G[v][j];
dp[i][v] = min(dp[i][v], dp[i - 1][o] + t);
}
}
}
int ans = INF;
for(int i = 1; i <= n; i++) ans = min(ans, dp[L][i]);
printf("%d\n", ans);
}
return 0;
}