P5764 [CQOI2005]新年好
我们可以发现总方案数为5!=120种,所以我们可以求出这六个点作为起点的单源最短距离,在枚举每种方案数求出最小值。
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
#include<vector>
#include<unordered_map>>
using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
#define inf 0x3f3f3f3f
const int N = 50010,M=200010;
int n,m,A,B,C,D,E;
int dist[N],ne[M],w[M],e[M],idx,h[N];
int dista[N], distb[N], distc[N], distd[N], diste[N];
bool st[N];
inline void add(int a,int b,int c){
e[idx]=b,ne[idx]=h[a],w[idx]=c,h[a]=idx++;
}
void dij(int x,int d[]){
priority_queue<pii,vector<pii>,greater<pii>>q;
memset(st,0,sizeof st);
for(register int i=1;i<=n;i++)d[i]=0x3f3f3f3f;
d[x]=0;
q.push({0,x});
while(q.size()){
int a=q.top().second;
q.pop();
if(st[a])continue;
st[a]=1;
for(register int i=h[a];i!=-1;i=ne[i]){
int j=e[i];
if(d[j]>d[a]+w[i]){
d[j]=d[a]+w[i];
if(!st[j])q.push({d[j],j});
}
}
}
}
int ans=2e9,cnt;
vector<int>path;
unordered_map<int,bool>s;
inline void dfs(int u){
if(u==5){
int res=dist[path[0]];
for(register int i(1);i<5;i++)
{
if(path[i]==A){
res+=dista[path[i-1]];
}
else if(path[i]==B){
res+=distb[path[i-1]];
}
else if(path[i]==C){
res+=distc[path[i-1]];
}
else if(path[i]==D){
res+=distd[path[i-1]];
}
else {
res+=diste[path[i-1]];
}
}
ans=min(ans,res);
return ;
}
for(auto it =s.begin();it!=s.end();it++){
int a=it->first,b=it->second;
if(!b){
s[a]=1;
path.push_back(a);
dfs(u+1);
path.pop_back();
s[a]=0;
}
}
}
int main(){
scanf("%d%d",&n,&m);
scanf("%d%d%d%d%d",&A,&B,&C,&D,&E);
memset(h,-1,sizeof h);
s[A]=s[B]=s[C]=s[D]=s[E]=0;
for(register int i(0);i<m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(b,a,c),add(a,b,c);
}
dij(1,dist);
dij(A,dista);
dij(B,distb);
dij(C,distc);
dij(D,distd);
dij(E,diste);
dfs(0);
cout<<ans<<endl;
return 0;
}