题目链接:http://icpc.njust.edu.cn/Problem/Hdu/2112/
只要需处理一下字符串,给他个编号再跑一半dijkstra就行。
代码如下:
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef unsigned int ui; 4 typedef long long ll; 5 typedef unsigned long long ull; 6 #define pf printf 7 #define mem(a,b) memset(a,b,sizeof(a)) 8 #define prime1 1e9+7 9 #define prime2 1e9+9 10 #define pi 3.14159265 11 #define lson l,mid,rt<<1 12 #define rson mid+1,r,rt<<1|1 13 #define scand(x) scanf("%llf",&x) 14 #define f(i,a,b) for(int i=a;i<=b;i++) 15 #define scan(a) scanf("%d",&a) 16 #define mp(a,b) make_pair((a),(b)) 17 #define P pair<int,int> 18 #define dbg(args) cout<<#args<<":"<<args<<endl; 19 #define inf 0x3f3f3f3f 20 const int maxn=200; 21 int n,m,t; 22 char st[maxn],ed[maxn],num[10005][maxn]; 23 int edge[maxn][maxn],d[maxn]; 24 int cnt=0; 25 int find(char* s) 26 { 27 if(cnt==0) 28 { 29 strcpy(num[0],s); 30 cnt=1; 31 return 0; 32 } 33 f(i,0,cnt-1) 34 { 35 if(strcmp(s,num[i])==0)return i; 36 } 37 strcpy(num[cnt],s); 38 cnt++; 39 return cnt-1; 40 } 41 void init() 42 { 43 cnt=0; 44 mem(edge,inf); 45 } 46 void dijkstra(int src) 47 { 48 f(i,0,cnt-1)d[i]=inf; 49 d[src]=0; 50 priority_queue<P,vector<P>,greater<P> >q; 51 q.push(mp(0,src)); 52 while(!q.empty()) 53 { 54 P now=q.top(); 55 q.pop(); 56 int u=now.second; 57 if(d[u]<now.first)continue; 58 f(i,0,cnt-1) 59 { 60 if(edge[u][i]!=inf&&d[i]>d[u]+edge[u][i]) 61 { 62 d[i]=d[u]+edge[u][i]; 63 q.push(mp(d[i],i)); 64 } 65 } 66 } 67 } 68 int main() 69 { 70 //freopen("input.txt","r",stdin); 71 //freopen("output.txt","w",stdout); 72 std::ios::sync_with_stdio(false); 73 while(scan(n)) 74 { 75 if(n==-1)break; 76 init(); 77 scanf("%s",st); 78 int s=find(st); 79 scanf("%s",ed); 80 int e=find(ed); 81 int a,b,w; 82 f(i,1,n) 83 { 84 scanf("%s%s%d",&st,&ed,&w); 85 a=find(st); 86 b=find(ed); 87 if(edge[a][b]>w)edge[a][b]=edge[b][a]=w;//注意这是一个无向图 88 } 89 dijkstra(s); 90 if(d[e]!=inf) 91 pf("%d ",d[e]); 92 else pf("-1 "); 93 } 94 }