Code: Select all
/*
Problem name: Babel
Author : Shiplu
Algorithm : Dijkstra
*/
#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;
struct abc
{
int x,cost,ch;
}temp,u;
struct comp
{
bool operator()(const abc &a,const abc &b)
{
return a.cost>b.cost;
}
};
char str[4005][53];
int d[4005],inf=1077952576,m;
vector< pair <int , int> > G[4005];
int findStore(char *x)
{
int i;
for(i=0;i<m;i++)
if(!strcmp(str[i],x))
break;
if(i==m)
strcpy(str[m++],x);
return i;
}
int main()
{
int i,n,start,end,j,k,in=1<<6;
pair<int,int> v;
char x[55],y[55],word[4005][55];
while(scanf("%d",&n)==1)
{
if(n==0)
break;
m=0;
scanf("%s %s",x,y);
start=findStore(x);
end=findStore(y);
memset(d,in,sizeof(d));
for(i=0;i<4002;i++)
G[i].clear();
for(i=0;i<n;i++)
{
scanf("%s %s %s",x,y,word[i]);
j=findStore(x);
k=findStore(y);
G[j].push_back(make_pair(k,strlen(word[i])));
G[k].push_back(make_pair(j,strlen(word[i])));
}
d[start]=0;
priority_queue<abc,vector<abc>,comp> Q;
temp.x=start;
temp.cost=0;
temp.ch=0;
Q.push(temp);
while(!Q.empty())
{
u=Q.top();
Q.pop();
if(u.cost>d[u.x])
continue;
for(i=G[u.x].size()-1;i>=0;i--)
{
v=G[u.x][i];
if(u.ch!=word[v.first][0]-96 && d[u.x]+v.second<d[v.first])
{
d[v.first]=d[u.x]+v.second;
temp.x=v.first;
temp.cost=d[v.first];
temp.ch=word[v.first][0]-96;
Q.push(temp);
}
}
}
if(d[end]<inf)
printf("%d\n",d[end]);
else
printf("impossivel\n");
}
return 0;
}