标签:
SPFA+枚举。
每条边的权值都设置一次为0 用一次SPFA,算出最短路,每次的最短路取最小值就是答案。
#include<stdio.h> #include<string.h> #include<math.h> #include<map> #include<queue> #include<vector> #include<string> #include<iostream> #include<algorithm> using namespace std; const int maxn=210; map<string,int>zh; vector<int>ljb[maxn]; int cost[maxn][maxn];//邻接矩阵 string s,s1,s2; int qidian,zhongdian,n,id; int dist[maxn],flag[maxn]; void spfa() { int iii; queue<int>Q; memset(flag,0,sizeof(flag)); for(iii=0;iii<id;iii++) dist[iii]=999999999; dist[qidian]=0;Q.push(qidian);flag[qidian]=1; while(!Q.empty()) { int h=Q.front(); Q.pop(); flag[h]=0; for(iii=0;iii<ljb[h].size();iii++) { if(cost[h][ljb[h][iii]]!=999999999) { if(dist[h]+cost[h][ljb[h][iii]]<dist[ljb[h][iii]]) { dist[ljb[h][iii]]=dist[h]+cost[h][ljb[h][iii]]; if(flag[ljb[h][iii]]==0) { Q.push(ljb[h][iii]); flag[ljb[h][iii]]=1; } } } } } } int main() { int i,j,cc; while(cin>>s) { for(i=0;i<210;i++) ljb[i].clear(); zh.clear(); id=1; zh[s]=id;id++; qidian=1;zhongdian=2;cin>>s; zh[s]=id;id++; scanf("%d",&n); for(i=0;i<=205;i++) { for(j=0;j<=205;j++) { if(i==j) cost[i][j]=0; else cost[i][j]=999999999; } } for(i=0;i<n;i++) { cin>>s1>>s2>>cc; if(zh[s1]==0)zh[s1]=id,id++; if(zh[s2]==0)zh[s2]=id,id++; cost[zh[s1]][zh[s2]]=cc; ljb[zh[s1]].push_back(zh[s2]); } int anss=999999999; for(i=1;i<id;i++) { for(j=1;j<id;j++) { if(i!=j&&cost[i][j]!=999999999) { int t=cost[i][j]; cost[i][j]=0; spfa(); if(dist[zhongdian]<anss) anss=dist[zhongdian]; cost[i][j]=t; } } } printf("%d\n",anss); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zufezzt/p/4514753.html