分析:SPFA的一个板子题,注意是双向建边,还有是把0当作一个虚拟的起点,以后都把无穷大设成是0x3f3f3f3f
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 5e3 + 10;
int t, s, d;
struct EDGE {
int next;int to;int w;
} edge[maxn];
int cnt = 0;
int head[maxn], dis[maxn];
int vis[maxn];
void add(int u, int v, int w) {
edge[cnt].w = w;edge[cnt].to = v;edge[cnt].next = head[u];head[u] = cnt++;
}
void spfa() {
memset(dis, inf, sizeof (dis));memset(vis, 0, sizeof(vis));queue<int> q;q.push(0);dis[0] = 0;vis[0] = 1;while (!q.empty()) {
int now = q.front();q.pop();vis[now] = 0;for (int i = head[now]; i != -1; i = edge[i].next) {
int to = edge[i].to;if (dis[to] > dis[now] + edge[i].w) {
dis[to] = dis[now] + edge[i].w;if (vis[to]!=-1) {
vis[to] = 1;q.push(to);}}}}int ans = inf;int p;for (int i = 1; i <= d; ++i) {
cin >> p;ans = min(ans, dis[p]);}cout<<ans<<endl;
}
int main() {
int a, b, time;while (cin >> t >> s >> d) {
//有T条路,与家相邻的城市有s个,草儿想去的地方有d个memset(head, -1, sizeof(head));cnt = 0;for (int i = 0; i < t; i++) {
cin >> a >> b >> time;add(a, b, time);add(b, a, time);}int u;for (int i = 0; i < s; i++) {
cin >> u;add(u, 0, 0);//此处需注意 add(0, u, 0);}spfa();}
}