1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include <bits/stdc++.h> #define ll long long #define int long long #define double long double #define N 14 #define Orz ios::sync_with_stdio(0),cin.tie(0) #define INF 2e18 #define rep(i,l,r) for(int i=l;i<=r;i++) #define pii pair<int,int> using namespace std; int n,m; vector<pii> edge[N]; int dis[N],dp[N][1<<N],pre[N][1<<N]; bool visit[N];
signed main(){ cin>>n>>m; rep(i,1,m){ int a,b,w;cin>>a>>b>>w; edge[a].push_back({b,w}); edge[b].push_back({a,w}); } int S = 0,start = -1;cin>>m; rep(i,1,m){ int temp;cin>>temp; S = S|(1<<temp); if(start == -1)start = temp; } rep(i,0,n)rep(j,0,(1<<n))dp[i][j] = INF; rep(i,0,n)dp[i][0] = 0; for(int i=1;i<(1<<n);i++){ if(i == (S & i)){ priority_queue<pii,vector<pii>,greater<pii>> pq; fill(dis,dis+n,INF); memset(visit,0,sizeof(visit)); for(int j=0;j<n;j++){ if(i&(1<<j)){ dis[j] = dp[j][i^(1<<j)]; pq.push({dis[j],j}); } } while(!pq.empty()){ int cur = pq.top().second; pq.pop(); visit[cur] = 1; for(auto k : edge[cur]){ int v = k.first,w = k.second; if(i&(1<<v))continue; if(dis[v] > dis[cur]+w){ dis[v] = dis[cur] + w; pre[v][i] = cur; pq.push({dis[v],v}); } else if(dis[v] == dis[cur]+w && pre[v][i] > cur){ pre[v][i] = cur; } } } for(int j=0;j<n;j++){ if(i & (1 << j))continue; dp[j][i] = dis[j]; } } } cout<<"Minimum travel distance: "<<dp[start][S^(start)]<<endl; cout<<"Travel route:"; int cur = start;S = S^(1<<start); while(true){ cout<<" "<<cur; if(!S)break; cur = pre[cur][S]; if(S&(1<<cur))S = (S^(1<<cur)); } cout<<endl; }
|