通过1≤K≤17比较容易看出这道题目需要用状压dp,先处理出c[i]到其他点的最短距离,然后状压更新当前路径的最小答案,最后枚举一下终点得到答案。
// #pragma GCC optimize(2)
// #include <random>
// #include <windows.h>
// #include <ctime>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <set>
#include <map>
#define IO \
ios::sync_with_stdio(false); \
// cout.tie(0);
#define lson(x) node << 1, start, mid
#define rson(x) node << 1 | 1, mid + 1, end
using namespace std;
// int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> P;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 10;
const int maxm = 1e2 + 10;
const LL mod = 1e9 + 7;
const double eps = 1e-8;
const double pi = acos(-1);
// int dis[4][2] = {1, 0, 0, -1, 0, 1, -1, 0};
// int m[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
struct Edge
{
int next, to;
} e[maxn << 1];
int head[maxn];
int d[maxn];
int dis[20][20];
int f[1 << 19][20];
int a[20];
int n, m, kk;
int k = 0;
void add(int u, int v)
{
e[k].next = head[u];
e[k].to = v;
head[u] = k++;
}
void BFS(int s)
{
memset(d, inf, sizeof d);
queue<int> q;
q.push(s);
d[s] = 0;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = head[u]; ~i; i = e[i].next)
{
int v = e[i].to;
if (d[v] == inf)
{
d[v] = d[u] + 1;
q.push(v);
}
}
}
return;
}
int main()
{
#ifdef WXY
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
IO;
int x, y;
memset(head, -1, sizeof head);
memset(dis, inf, sizeof dis);
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> x >> y;
add(x, y);
add(y, x);
}
cin >> kk;
for (int i = 1; i <= kk; i++)
cin >> a[i];
for (int i = 1; i <= kk; i++)
{
BFS(a[i]);
for (int j = 1; j <= kk; j++)
dis[i][j] = d[a[j]];
}
memset(f, inf, sizeof f);
for (int i = 0; i < kk; i++)
f[1 << i][i + 1] = 1;
int all = (1 << kk) - 1;
for (int i = 1; i <= all; i++)
{
for (int j = 1; j <= kk; j++)
{
if (f[i][j] == inf)
continue;
for (int t = 1; t <= kk; t++)
{
if (j == t)
continue;
if (!(i >> (t - 1) & 1))
{
int nex = i + (1 << (t - 1));
f[nex][t] = min(f[nex][t], f[i][j] + dis[j][t]);
}
}
}
}
int ans = inf;
for (int i = 1; i <= kk; i++)
{
ans = min(ans, f[all][i]);
}
if (ans == inf)
cout << -1;
else
cout << ans;
return 0;
}