http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4170
d[i,j]前i个字符j结尾
d[i,j]=min{d[i-1,k], j和k有边}+(a[i]!=j)
初始化d[1,j]=1, d[1,a[1]]=0
#include <cstdio> #include <cstring> #include <cmath> #include <string> #include <iostream> #include <algorithm> #include <queue> #include <set> #include <map> using namespace std; typedef long long ll; #define pii pair<int, int> #define mkpii make_pair<int, int> #define pdi pair<double, int> #define mkpdi make_pair<double, int> #define pli pair<ll, int> #define mkpli make_pair<ll, int> #define rep(i, n) for(int i=0; i<(n); ++i) #define for1(i,a,n) for(int i=(a);i<=(n);++i) #define for2(i,a,n) for(int i=(a);i<(n);++i) #define for3(i,a,n) for(int i=(a);i>=(n);--i) #define for4(i,a,n) for(int i=(a);i>(n);--i) #define CC(i,a) memset(i,a,sizeof(i)) #define read(a) a=getint() #define print(a) printf("%d", a) #define dbg(x) cout << (#x) << " = " << (x) << endl #define error(x) (!(x)?puts("error"):0) #define printarr2(a, b, c) for1(_, 1, b) { for1(__, 1, c) cout << a[_][__]; cout << endl; } #define printarr1(a, b) for1(_, 1, b) cout << a[_] << '\t'; cout << endl inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; } inline const int max(const int &a, const int &b) { return a>b?a:b; } inline const int min(const int &a, const int &b) { return a<b?a:b; } const int N=505; int mp[N][N], a[N], len, d[N][N], n, m; void add(int u, int v) { mp[u][v]=mp[v][u]=1; } int main() { int cs=getint(); while(cs--) { read(n); read(m); CC(mp, 0); CC(d, 0x3f); for1(i, 1, n) add(i, i); for1(i, 1, m) add(getint(), getint()); read(len); for1(i, 1, len) read(a[i]); for1(i, 1, n) d[1][i]=1; d[1][a[1]]=0; for1(i, 2, len) for1(j, 1, n) for1(k, 1, n) if(mp[j][k]) d[i][j]=min(d[i][j], d[i-1][k]+(a[i]!=j)); int ans=~0u>>1; for1(i, 1, n) ans=min(ans, d[len][i]); printf("%d\n", ans); } return 0; }