Dijkstra求最短路,说到底还是暴力枚举了每条边免费的情况,不算好算法
#include<stdio.h>
#include<string.h>
#include<limits.h>
static char city[100][11];
static int total;
static int map[100][100];
static int find_city(char *s)
{
int i;
for (i = 0; i < total; i++)
if (strcmp(s, city[i]) == 0)
return i;
strcpy(city[total], s);
return total++;
}
static int dijkstra(int from, int to, int freed)
{
int i, known[100], d[100];
memset(known, 0, sizeof(known));
for (i = 0; i < total; i++)
d[i] = INT_MAX;
d[from] = 0;
int now = from, next;
while (1)
{
known[now] = 1;
int mind = INT_MAX;
for (i = 0; i < total; i++)
{
if (map[now][i] != -1 && !known[i] && map[now][i] <= freed
&& d[now] + map[now][i] < d[i])
d[i] = d[now] + map[now][i];
if (!known[i] && d[i] < mind)
{
mind = d[i];
next = i;
}
}
now = next;
if (mind == INT_MAX)
return INT_MAX;
if (now == to)
return d[to];
}
return INT_MAX;
}
int main()
{
char src[11], dst[11];
while (scanf("%s %s", src, dst) != EOF)
{
int m, cost, i, j;
char s[11], t[11];
scanf("%d", &m);
getchar();
total = 0;
memset(map, -1, sizeof(map));
while (m--)
{
scanf("%s %s %d", s, t, &cost);
getchar();
int ss = find_city(s);
int tt = find_city(t);
map[ss][tt] = map[tt][ss] = cost;
}
int from = find_city(src);
int to = find_city(dst);
int res = INT_MAX;
for (i = 0; i < total; i++)
for (j = i; j < total; j++)
if (map[i][j] != -1)
{
int temp = map[i][j];
map[i][j] = map[j][i] = 0;
int dd = dijkstra(from, to, temp);
if (dd < res)
res = dd;
map[i][j] = map[j][i] = temp;
}
printf("%d\n", res);
}
return 0;
}