HDU 2680 Choose the best route 最短路 多起點單終點 SPFA

/*
 * 解題總結 :
 *      1 : 可以把多個起點聚集到一個超級源點上,這裏用了1010這個點。
 *      2 : 然後用這個超級源點跑一次最短路就行了。
 */
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3 + 100;
const int MAXM = 3e4 + 10;
const int INF = 0x3f3f3f3f;

struct E{
    int to, w, nxt;
}edge[MAXM];
queue<int> q;
int tot, head[MAXN], dis[MAXN], inqtot[MAXN], n, m, e;
bool inq[MAXN];

inline void clear(){
    tot = 0;
    memset(head, -1, sizeof head);
    memset(dis, INF, sizeof dis);
    dis[1010] = 0;
    memset(inqtot, 0, sizeof inqtot);
    memset(inq, false, sizeof inq);
    while(!q.empty()) q.pop();
}

inline void addedge(int u, int v, int w){
    edge[tot].to = v;
    edge[tot].w = w;
    edge[tot].nxt = head[u];
    head[u] = tot++;
}

inline bool SPFA(){
    q.push(1010);
    inq[1010] = true;
    ++inqtot[1010];
    while(!q.empty()){
        int id = q.front();
        q.pop();
        inq[id] = false;
        for(int i = head[id]; ~i; i = edge[i].nxt){
            int to = edge[i].to;
            int w = edge[i].w;
            if(dis[id] + w < dis[to]){
                dis[to] = dis[id] + w;
                if(!inq[to]){
                    inq[to] = true;
                    ++inqtot[to];
                    q.push(to);
                    if(inqtot[to] > n) return false;
                }
            }
        }
    }
    return true;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    //cout << setiosflags(ios::fixed) << setprecision(1); //保留小數點後1位
    //cout << setprecision(1); //保留1位有效數字
//    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);

    while(cin >> n >> m >> e){
        clear();
        for(int i = 1; i <= m; ++i) {
            int u, v, w;
            cin >> u >> v >> w;
            addedge(u, v, w);
        }
        int W;
        cin >> W;
        for(int i = 1, x; i <= W; ++i){
            cin >> x;
            addedge(1010, x, 0);
        }
        bool ok = SPFA();
        if(!ok) continue;
        if(dis[e] == INF) cout << -1 << endl;
        else cout << dis[e] << endl;
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章