标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3154 Accepted Submission(s): 1026
#include <stdio.h> #include <algorithm> #include <string.h> #include <math.h> #include <queue> using namespace std; const int N = 1005; const int INF = 99999999; struct Node{ char s[5],e[5]; int w; }node[N]; int graph[N][N]; int n; void deal(char s[],int id){ for(int i=0;i<4;i++) node[id].s[i] = s[i]; int len = strlen(s); int k =0; for(int i=len-4;i<len;i++) { node[id].e[k++] = s[i]; } } int low[N]; bool vis[N]; void dijkstra(int s){ memset(vis,false,sizeof(vis)); for(int i=0;i<n;i++){ low[i] = (i==s)?0:graph[s][i]; } vis[s] = true; for(int i=1;i<n;i++){ int Min = INF; for(int j=0;j<n;j++){ if(Min>low[j]&&!vis[j]){ s=j; Min = low[j]; } } vis[s] = true; for(int j=0;j<n;j++){ if(low[j]>low[s]+graph[s][j]&&!vis[j]){ low[j]=low[s]+graph[s][j]; } } } } int main() { while(scanf("%d",&n)!=EOF&&n){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j) graph[i][j] = 0; else graph[i][j]=INF; } } for(int i=0;i<n;i++){ char str[N]; scanf("%d%s",&node[i].w,str); deal(str,i); } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(strcmp(node[i].e,node[j].s)==0) graph[i][j] = node[i].w; } } dijkstra(0); if(low[n-1]>=INF) printf("-1\n"); else printf("%d\n",low[n-1]); } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5489814.html