单源最短路 : 多起点

https://www.acwing.com/problem/content/1139/

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
const int N = 1e3 + 7, M = 2e4 + 7;
int h[N], ne[M], e[M], w[M], idx;
int dist[N];
bool st[N];
int n, m, s, t;

void add(int a, int b, int c) {
    ne[idx] = h[a], e[idx] = b, w[idx] = c, h[a] = idx++;
}

void dijkstra() {
    int t;
    cin >> t;
    memset(dist, 0x3f, sizeof dist);
    memset(st, 0, sizeof st);
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    while (t--) {
        int u;
        cin >> u;
        dist[u] = 0;
        heap.push({0, u});
    }
    while (heap.size()) {
        auto t = heap.top();
        heap.pop();
        int ver = t.se, d = t.fi;
        if (st[ver]) continue;
        st[ver] = true;
        for (int i = h[ver]; ~i; i = ne[i]) {
            int j = e[i];
            if (dist[j] > d + w[i]) {
                dist[j] = d + w[i];
                heap.push({dist[j], j});
            }
        }
    }
}

int main() {
    IO;
    while(cin >> n >> m >> s) {
        memset(h, -1 ,sizeof h);
        idx = 0;
        while (m--) {
            int a, b, c;
            cin >> a >> b >> c;
            add(a, b, c);
        }
        dijkstra();
        if (dist[s] == inf) dist[s] = -1;
        cout << dist[s] << '\n';
    }
    return 0;
}
posted @ 2021-02-10 17:00  phr2000  阅读(52)  评论(0编辑  收藏  举报