问题描述
在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
输入
输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。输入保证至少存在1条商店到赛场的路线。 当输入为两个0时,输入结束。
输出
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间。
输入例子 1
3 3
1 2 1
2 3 1
1 3 3
3 3
1 2 2
2 3 1
1 3 1
0 0
输出例子
2
1
实现代码
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int Inf = 0x3f3f3f3f;
const int maxn = 100 + 5;
const int maxm = 10000 + 5;
int head[maxn], inq[maxn], dis[maxn];
int cnt = 0;
struct Edge {
int next, to, time;
Edge() {}
Edge(int next, int to, int time) : next(next), to(to), time(time) {}
}edges[maxm];
void Link(int from, int to, int time) {
edges[++cnt] = Edge(head[from], to, time);
head[from] = cnt;
}
void spfa(int s, int e) {
memset(dis, Inf, sizeof(dis));
memset(inq, 0, sizeof(inq));
queue<int> q;
q.push(s);
dis[s] = 0, inq[s] = 1;
while (q.size()) {
int now = q.front(); q.pop();
inq[now] = 0;
for (int i = head[now]; i; i = edges[i].next) {
int to = edges[i].to, time = edges[i].time;
if (dis[to] > dis[now] + time) {
dis[to] = dis[now] + time;
if (!inq[to]) {
q.push(to);
inq[to] = 1;
}
}
}
}
cout<< dis[e] <<endl;
}
int main() {
int n, m, a, b, c;
while (cin >> n >> m)
{
if (!n && !m) break;
cnt = 0;
memset(head, 0, sizeof(head));
while (m--)
{
cin >> a >> b >> c;
Link(a, b, c);
Link(b, a, c);
}
spfa(1, n);
}
return 0;
}
在学校的垃圾OJ运行错误,在杭电AC了,emm,不愧是高建。