标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 758 Accepted Submission(s): 254
#include <iostream> #include <cstdio> #include <string.h> #include <queue> #include <algorithm> #include <math.h> using namespace std; typedef long long LL; const LL INF = 999999999999; const LL N = 100005; struct Edge{ LL v,next; LL w; }edge[2*N]; struct City{ LL id,idx; }c[20]; LL head[N]; LL tot,n,m,Q; bool vis[N]; LL low[N]; LL dis[15][15]; LL MIN ; void addEdge(LL u,LL v,LL w,LL &k){ edge[k].v = v,edge[k].w = w,edge[k].next = head[u],head[u]=k++; } void init(){ memset(head,-1,sizeof(head)); tot = 0; for(LL i=0;i<15;i++){ for(LL j=0;j<15;j++){ dis[i][j] = INF; } } } void spfa(LL pos){ for(LL i=0;i<n;i++){ low[i] = INF; vis[i] = false; } low[pos] = 0; queue<LL>q; q.push(pos); while(!q.empty()){ LL u = q.front(); q.pop(); vis[u] = false; ///!!!!!!!!!!!!!!!!!! for(LL k=head[u];k!=-1;k=edge[k].next){ LL w = edge[k].w,v = edge[k].v; if(low[v]>low[u]+w){ low[v] = low[u]+w; if(!vis[v]){ vis[v] = true; q.push(v); } } } } } bool vis1[20]; void dfs(LL u,LL step,LL ans){ vis1[u] = true; if(step==Q){ MIN = min(MIN,ans+dis[u][0]); return; } for(LL i=0;i<=Q;i++){ if(!vis1[i]&&dis[u][i]<INF){ dfs(i,step+1,ans+dis[u][i]); vis1[i] = false; } } } int main(){ int tcase; scanf("%d",&tcase); while(tcase--){ init(); scanf("%lld%lld",&n,&m); for(LL i=1;i<=m;i++){ LL u,v,w; scanf("%lld%lld%lld",&u,&v,&w); addEdge(u,v,w,tot); addEdge(v,u,w,tot); } scanf("%lld",&Q); c[0].id = 0; c[0].idx = 0; for(LL i=1;i<=Q;i++){ scanf("%lld",&c[i].id); c[i].idx = i; } for(LL i=0;i<=Q;i++){ spfa(c[i].id); for(LL j=0;j<=Q;j++){ dis[c[i].idx][c[j].idx] = low[c[j].id]; } } /* for(LL i=0;i<=Q;i++){ for(LL j=0;j<=Q;j++){ printf("%lld ",dis[i][j]); } printf("\n"); }*/ MIN = INF; memset(vis1,false,sizeof(vis1)); dfs(0,0,0); printf("%lld\n",MIN); } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5692586.html