思路:
暴力,O(n * (n1) ^ 2)。
dp[i][j]表示第i位是j的最优解。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vll;
const int MAXN = 1e6 + 10;
const ll INF = 0x3f3f3f3f;
const ll MOD = 1e9 + 7;
const double eps = 1e-8;
const double PI = acos(-1.0);
int n, m, k;
vi p;
vii dp, g;
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
cout << setprecision(10) << fixed;
int times;
cin >> times;
while(times--){
cin >> n >> m;
g.clear();
g.resize(n, vi(n));
for(int i = 0; i < m; i++){
int u, v;
cin >> u >> v;
u--;
v--;
g[u][v] = g[v][u] = 1;
}
for(int i = 0; i < n; i++)
g[i][i] = 1;
cin >> k;
p.clear();
p.resize(k);
for(int i = 0; i < k; i++){
cin >> p[i];
p[i] -= 1;
}
dp.clear();
dp.resize(k, vi(n));
for(int i = 0; i < n; i++)
dp[0][i] = (p[0] != i);
for(int i = 1; i < k; i++)
for(int j = 0; j < n; j++){
int cur = INF;
for(int t = 0; t < n; t++)
if(g[t][j])
cur = min(cur, dp[i - 1][t]);
dp[i][j] = cur + (p[i] != j);
}
int res = INF;
for(int i = 0; i < n; i++)
res = min(res, dp[k - 1][i]);
cout << res << endl;
}
cerr << "execute time : " << (double)clock() / CLOCKS_PER_SEC << endl;
return 0;
}
未来可期。