zoj2750
#include<iostream> #include<cstring> #include<cstdio> #include<string> #include<algorithm> using namespace std; const int inf = 1000000000; const int maxn = 1010; int edge[maxn][maxn]; int s[maxn],dist[maxn],i,j,n; struct node { int t ; char front[5],back[5]; }dict[maxn]; void dijkstra() { for(i=0;i<n;i++) { dist[i] = edge[0][i]; s[i] = 1; } s[0] = -1; for(i=1;i<n;i++) { int min = inf,v=0; for(j=0;j<n;j++) { if(s[j]!=-1 && dist[j]<min) { min = dist[j]; v = j; } } s[v] = -1; for(j=0;j<n;j++) { if(s[j]!=-1 && edge[v][j]<inf && edge[v][j]+dist[v]<dist[j]) { dist[j] = edge[v][j] + dist[v]; } } } if(dist[n-1] == inf) printf("-1\n"); else { printf("%d\n",dist[n-1]); } } int main() { // int n; while(scanf("%d",&n)!=EOF && n) { int k;char d[100]; for(k=0;k<n;k++) { scanf("%d %s",&dict[k].t,d); int len = strlen(d); for(i=0,j=len-1;i<4;i++,j--) { dict[k].front[i] = d[i]; dict[k].back[3-i] = d[j]; dict[k].front[4] = dict[k].back[4] = '\0'; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { edge[i][j] = inf; if(i==j) edge[i][j] = 0; // continue; else if(strcmp(dict[i].back,dict[j].front) ==0) { edge[i][j] = dict[i].t; } } } dijkstra(); } return 0; }