标签:
1 #include<map> 2 #include<queue> 3 #include<cstdio> 4 #include<string> 5 #include<cstring> 6 #include<algorithm> 7 using namespace std; 8 9 struct edge 10 { 11 int from,to,time; 12 edge(int u,int v,int w):from(u),to(v),time(w){}; 13 }; 14 15 struct Node 16 { 17 int st; 18 int ed; 19 int val; 20 }node[1005]; 21 22 struct heapnode 23 { 24 int u,d; 25 bool operator < (const heapnode &temp)const 26 { 27 return d>temp.d; 28 } 29 }; 30 31 const int inf =0x3f3f3f3f; 32 map<string,int>key; 33 vector<edge>edges; 34 vector<int>G[1005]; 35 int d[1005],vis[1005]; 36 int num,n; 37 38 void init() 39 { 40 for(int i=0;i<n;i++) 41 G[i].clear(); 42 edges.clear(); 43 memset(vis,0,sizeof(vis)); 44 key.clear(); 45 } 46 47 void addedge(int u,int v,int w) 48 { 49 edges.push_back(edge(u,v,w)); 50 int m=edges.size(); 51 G[u].push_back(m-1); 52 } 53 54 void dijkstra(int S) 55 { 56 priority_queue<heapnode>q; 57 q.push((heapnode){S,0}); 58 for(int i=0;i<n;i++) 59 d[i]=inf; 60 d[S]=0; 61 while(!q.empty()) 62 { 63 int u=q.top().u; 64 q.pop(); 65 if(vis[u]) 66 continue; 67 vis[u]=1; 68 for(int i=0;i<G[u].size();i++) 69 { 70 edge& e=edges[G[u][i]]; 71 if(d[e.to]>d[u]+e.time) 72 { 73 d[e.to]=d[u]+e.time; 74 q.push((heapnode){e.to,d[e.to]}); 75 } 76 } 77 } 78 } 79 80 int main() 81 { 82 //freopen("in.txt","r",stdin); 83 char s[105],sub1[5],sub2[5]; 84 string temp1,temp2; 85 int i,j,val,t,k; 86 while(scanf("%d",&t),t) 87 { 88 j=num=0; 89 n=t; 90 init(); 91 while(t--) 92 { 93 scanf("%d %s",&val,s); 94 int len=strlen(s); 95 for(i=0;i<4;i++) 96 sub1[i]=s[i]; 97 sub1[i]=‘\0‘; 98 temp1=sub1; 99 if(!key.count(temp1)) 100 key[temp1]=num++; 101 for(k=0,i=len-4;i<=len;i++,k++) 102 sub2[k]=s[i]; 103 temp2=sub2; 104 if(!key.count(temp2)) 105 key[temp2]=num++; 106 node[j].st=key[temp1]; 107 node[j].ed=key[temp2]; 108 node[j].val=val; 109 for(int k=0;k<j;k++) 110 if(node[k].ed==node[j].st) 111 addedge(k,j,node[k].val); 112 else if(node[j].ed==node[k].st) 113 addedge(j,k,node[j].val); 114 else; 115 j++; 116 } 117 dijkstra(0); 118 if(d[n-1]==inf) 119 printf("-1\n"); 120 else 121 printf("%d\n",d[n-1]); 122 } 123 return 0; 124 }
HDU 1546 Idiomatic Phrases Game(dijkstra+优先队列)
标签:
原文地址:http://www.cnblogs.com/homura/p/4725013.html