题意:有从1到n的数字组成一个无向连通图,给出了连通情况,然后给出一个数字序列,问这个序列要求相邻的点要么相等要么在图中是直接连通的,问最少修改序列中的几个点可以让序列满足要求。
题解:f[i][j]表示前i个数组组成的序列以数字j结尾的最少修改点,那么f[i][j] = min{f[i][j],f[i - 1][k] + (d[i] != j)},此时j==k或g[j][k] == 1。最后f[len][k]所有数字过一遍选出最大值就可以了。
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int N = 205; const int INF = 0x3f3f3f3f; int n, m, g[N][N], d[N], f[N][N]; int main() { int t; scanf("%d", &t); while (t--) { scanf("%d%d", &n, &m); memset(g, 0, sizeof(g)); int a, b; for (int i = 0; i < m; i++) { scanf("%d%d", &a, &b); g[a][b] = g[b][a] = 1; } scanf("%d", &m); for (int i = 1; i <= m; i++) scanf("%d", &d[i]); memset(f, INF, sizeof(f)); for (int i = 1; i <= n; i++) f[1][i] = (i != d[1]); for (int i = 2; i <= m; i++) for (int j = 1; j <= n; j++) for (int k = 1; k <= n; k++) if (j == k || g[j][k]) f[i][j] = min(f[i][j], f[i - 1][k] + (j != d[i])); int res = INF; for (int i = 1; i <= n; i++) res = min(res, f[m][i]); printf("%d\n", res); } return 0; }
时间: 2024-08-03 07:01:45