Topic link: click here~
Topic
- n gems, m relationships ai, bi, indicating that gems ai and bi can be placed adjacently, and then k gems are numbered ci
- Ask how to string gems reasonably so that all k gems are included and the total number of gems used is the least
- Range 1≤N≤1e5, 0≤M≤1e5, 1≤ai<bi≤N, 1≤K≤17, 1≤Ci≤N
- m does not repeat the relationship
Ideas
- bfs+ state pressure dp
- These m relationships can be regarded as m edges, and the weight of the edges is 1, and then a shortest path is constructed so that all k points ci are run.
- Run k bfs, record dis[i][x], indicating the shortest path from point c[i] to point x
- The next task is to run through all the k points. If they are in order, they must be arranged. The factorial calculation of 17 is too big and it will be t
- Then dynamic programming, state pressure dp, transfer the binary state, dp[t][i] represents the shortest path to point c[i] in the state of t
- Then find the point j that has not been passed in the k points, and the state after adding the point j is t+(1<<j), then the transfer equation is dp[t+(1<<j)][j] = max(dp[t+(1<<j)][j], dp[t][i] + dis[i][c[j]]);
- The final state is binary k 1s, which is (1<<k)-1, then update the minimum value of dp[(1<<k)-1][i]
ac code
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e5 + 5;
const int inf = 0x3f3f3f3f;
int dis[20][maxn], c[20];
int dp[1<<17][20];
vector<int> v[maxn];
void bfs(int i){ //bfs跑最短路
int st = c[i];
queue<int> q;
q.push(st);
dis[i][c[i]] = 0;
while(q.size()){
int t = q.front(); q.pop();
for(auto it : v[t]){
if(dis[i][it] == inf){
dis[i][it] = dis[i][t] + 1;
q.push(it);
}
}
}
}
int main(){
int n, m;
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i ++){
int x, y;
scanf("%d%d", &x, &y);
v[x].push_back(y);
v[y].push_back(x);
}
int k; scanf("%d", &k);
for(int i = 0; i < k; i ++) scanf("%d", &c[i]);
memset(dis, inf, sizeof(dis));
memset(dp, inf, sizeof(dp));
for(int i = 0; i < k; i ++){
bfs(i);
}
for(int i = 0; i < k; i ++){//初始点距离是0
dp[1<<i][i] = 0;
}
for(int t = 0; t < (1 << k); t ++){
for(int i = 0; i < k; i ++){
if(!((t >> i) & 1)) continue; //说明状态t中没有k个点中的第i个点,我们要跑到第i个点,所以这个状态不符合
for(int j = 0; j < k; j ++){
if((t >> j) & 1) continue;//说明状态t中有k个点中的第j个点, 现在要走到新点,所以跳
dp[t | (1 << j)][j] = min(dp[t | (1 << j)][j], dp[t][i] + dis[i][c[j]]); //dis表示k个点中第i个点跳到第j个点的最短路径
}
}
}
int ans = inf;
for(int i = 0; i < k; i ++){
ans = min(ans, dp[(1<<k) - 1][i] + 1); //算的是宝石的数量,我们求的是边的数量,所以还要加上初始点
}
if(ans == inf) ans = -1;
printf("%d\n", ans);
return 0;
}