SPFA

#include<bits/stdc++.h>

using namespace std;
const int N = 10000;
struct edge{
    int from,to,v;
    edge(int a,int b,int c){
        from=a;to=b;v=c;
    }
};
vector<edge> e[N];
int m,n,a,b,c,Inf=1e6;

int spfa(int u){
    int dis[N],neg[N];
    bool inq[N];
    for (int i = 1; i <= n; i++) {
        dis[i]=Inf,inq[i]=false;neg[i]=0;
    }
    neg[u]=1;
    dis[u]=0;
    queue<int> q;
    inq[u]=true;
    q.push(u);
    while(!q.empty()){
        int t=q.front();q.pop();
        inq[t]=false;
        for (int i = 0; i < e[t].size(); i++) {
            int v=e[t][i].to;
            int w=e[t][i].v;
            if (dis[t]+w<dis[v]){
                dis[v]=dis[t]+w;
                if (!inq[v]){  //状态更新
                    q.push(v);
                    inq[v]=true;
                    neg[v]++;
                    if(neg[v]>n) return false;
                }
            }
        }
    }
    cout<<dis[n]<<endl;
    return true;
}

int main(){
    ios::sync_with_stdio(false);
    cin>>m>>n;
    for (int i = 1; i <= m; i++) {
        cin>>a>>b>>c;
        e[a].push_back(edge(a,b,c));
        e[b].push_back(edge(b,a,c));
    }
    spfa(1);
}

 

posted @ 2021-05-20 22:01  limited_Infinite  阅读(30)  评论(0编辑  收藏  举报
// //返回顶部 //返回顶部按钮