HDU 1874 暢通工程續 最短路 SPFA

/*
 * 模板題
 */
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e2 + 10;
const int MAXM = 2e3 + 10;
const int INF = 0x3f3f3f3f;

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

inline void clear(){
    tot = 0;
    memset(head, -1, sizeof head);
    while(!q.empty()) q.pop();
    memset(dis, INF, sizeof dis);   //未初始化完
    memset(inq, false, sizeof inq);
    memset(inqtot, 0, sizeof inqtot);
}

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(s);
    inq[s] = true;
    ++inqtot[s];
    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){
        clear();
        for(int i = 1; i <= m; ++i){
            int u, v, w;
            cin >> u >> v >> w;
            addedge(u, v, w);
            addedge(v, u, w);
        }
        cin >> s >> e;
        dis[s] = 0;
        bool ok = SPFA();
        if(!ok) continue;
        if(dis[e] == INF) cout << -1 << endl;
        else cout << dis[e] << endl;
    }
    return 0;
}

 

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