zoukankan      html  css  js  c++  java
  • SPAF

    #include<bits/stdc++.h>
    #define re register
    
    using namespace std;
    
    const int N(100001);
    const int M(200001);
    const int INF(0x7fffffff);
    
    struct f1{
        int v;
        int w;
        int nxt;
    }e[M];
    
    int n,m,s,cnt;
    int head[N],dist[N],vis[N];//vis记录是否在队列里 
    
    struct node{
        int d;
        int u;
        node(int d1,int u1):d(d1),u(u1){};
    };
    
    bool operator > (const node &a,const node &b){
        return a.d>b.d;
    }
    
    priority_queue<node,vector<node>,greater<node> >q;
    
    int read(){
        int X=0,flag=1;
        char ch=getchar();
        while(ch>'9'||ch<'0') { if(ch=='-') flag=-1; ch=getchar(); }
        while(ch>='0'&&ch<='9') X=X*10+ch-48,ch=getchar();
        return X*flag;
    }
    
    void add(int u,int v,int w){
        e[++cnt].v=v;
        e[cnt].w=w;
        e[cnt].nxt=head[u];
        head[u]=cnt;
    }
    
    void get(){
        n=read(),m=read(),s=read();
        for(re int i=1;i<=m;++i){
            int u=read(),v=read(),w=read();
            add(u,v,w);
        }
    }
    
    void SPFA(){
        for(re int i=1;i<=n;++i) dist[i]=INF;
        dist[s]=0;
        q.push(node(dist[s],s));
        while(!q.empty()){
            node f=q.top();q.pop();
            int u=f.u;
            vis[u]=0;
            for(re int i=head[u];i;i=e[i].nxt){
                if(dist[e[i].v]>dist[u]+e[i].w){
                    dist[e[i].v]=dist[u]+e[i].w;
                    if(!vis[e[i].v]) q.push(node(dist[e[i].v],e[i].v)),vis[e[i].v]=1;
                }
            }
        }
    }
    
    int main(){
        get();
        SPFA();
        for(re int i=1;i<=n;++i)
            printf("%d ",dist[i]);
        return 0;
    }
  • 相关阅读:
    LeetCode18. 四数之和
    15. 三数之和
    LeetCode202. 快乐数
    LeetCode1. 两数之和
    LeetCode349. 两个数组的交集
    LeetCode242. 有效的字母异位词
    VSCode运行时弹出powershell
    关于cin, cin.get(), getchar(),getline()的字符问题
    剑指 Offer 27. 二叉树的镜像
    BFS zoj 1649
  • 原文地址:https://www.cnblogs.com/Adventurer-H/p/10884487.html
Copyright © 2011-2022 走看看