//最短路,需要注意的是,终点和起点有可能相同
//这里写了2个版本spfa和dijkstra
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
#define MAXN 200
#define INF 0x3f3f3f3f
char hash[MAXN][MAXN];
int pos, dis[MAXN], each_dis[MAXN][MAXN], used[MAXN];
int get_index(const char *str)
{
for(int i = 0; i < pos; i ++) {
if( !strcmp(hash[i], str) ) {
return i;
}
}
strcpy(hash[pos ++], str);
return pos-1;
}
int spfa(int src, int des, int vertex)
{
int u, v;
queue<int> q;
memset(used, 0, sizeof(used));
fill(dis, dis+vertex+1, INF);
q.push(src); used[src] = 1; dis[src] = 0;
while( !q.empty() ) {
u = q.front(); q.pop(); used[u] = 0;
for(v = 0; v < vertex; v ++) {
if( !each_dis[u][v] || dis[v] < dis[u]+each_dis[u][v] ) {
continue;
}
if( !used[v] ) {
q.push(v); used[v] = 1;
}
dis[v] = dis[u]+each_dis[u][v];
}
}
return (INF <= dis[des])? -1 : dis[des];
}
int dijkstra(int src, int des, int vertex)
{
int u, v, min_val;
for(int i = 0; i < vertex; i ++) {
dis[i] = (each_dis[src][i])? each_dis[src][i] : INF;
}
memset(used, 0, sizeof(used));
dis[src] = 0; used[src] = 1;
for(int i = 0; i < vertex; i ++) {
min_val = INF;
for(int j = 0; j < vertex; j ++) {
if( used[j] || min_val < dis[j] ) {
continue;
}
min_val = dis[j]; v = j;
}
u = v; used[u] = 1;
for(int j = 0; j < vertex; j ++) {
if( used[j] || !each_dis[u][j] || dis[j] < dis[u]+each_dis[u][j] ) {
continue;
}
dis[j] = dis[u]+each_dis[u][j];
}
}
return (INF == dis[des])? -1 : dis[des];
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
int n, t, uu, vv, idx, same, src, des;
char u[MAXN], v[MAXN];
while( scanf("%d", &n) && -1 != n ) {
pos = same = 0;
scanf("%s %s", u, v);
src = get_index(u); des = get_index(v);
if( !strcmp(u, v) ) {
printf("0\n"); same = 1;
}
memset(each_dis, 0, sizeof(each_dis));
for(int i = 0; i < n; i ++) {
scanf("%s %s %d", u, v, &t);
uu = get_index(u); vv = get_index(v);
each_dis[uu][vv] = each_dis[vv][uu] = t;
}
if( !same ) {
//printf("%d\n", spfa(src, des, pos));
printf("%d\n", dijkstra(src, des, pos));
}
}
return 0;
}
hdu_2112
最新推荐文章于 2021-07-25 17:07:39 发布