Dijktra单源最短路。。又坑了我一下午的时间,我发誓再也不用python写ACM了。。一模一样的算法,用python就TLE了,C的代码也才100MS啊,真心想不通啊,语言换来换去麻烦死。。以后就用C或JAVA了,手贱啊手贱,python在我印象大减,昨天也是一道题一直报Non zero exit code的错,调了我半天也无果,好无语啊。。
#include<stdio.h>
#include<string.h>
#include<limits.h>
static int end_equal_start(char *s, char *t)
{
int i, index = strlen(s) - 4;
for (i = 0; i < 4; i++)
if (s[index + i] != t[i])
return 0;
return 1;
}
int main()
{
char map[1000][1000], s[1000][100];
int n, time[1000], known[1000], d[1000];
while (scanf("%d", &n), n)
{
int i, j;
memset(map, 0, sizeof(map));
for (i = 0; i < n; i++)
scanf("%d %s", &time[i], s[i]);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (i != j && end_equal_start(s[i], s[j]))
map[i][j] = 1;
for (i = 0; i < n; i++)
d[i] = INT_MAX;
memset(known, 0, sizeof(known));
d[0] = 0;
int now = 0, next;
while (1)
{
known[now] = 1;
int mind = INT_MAX;
for (i = 0; i < n; i++)
{
if (map[now][i] && !known[i] && d[now] + time[now] < d[i])
d[i] = d[now] + time[now];
if (!known[i] && d[i] < mind)
{
mind = d[i];
next = i;
}
}
now = next;
if (mind == INT_MAX)
{
puts("-1");
break;
}
if (now == n - 1)
{
printf("%d\n", d[now]);
break;
}
}
}
return 0;
}