zoukankan      html  css  js  c++  java
  • SPFA队列模板

    #include<stdio.h>
    #include<iostream>
    #include<algorithm>
    #include<string.h>
    #include<string>
    #include<queue>
    
    using namespace std;
    const int maxn=2010;
    
    struct {
        int x,y,w,next;
    }e[maxn<<2];
    
    int dis[maxn],vis[maxn],head[maxn],cnt[maxn];
    
    int addedge(int x,int y,int w,int k)
    {
        e[k].x=x,e[k].y=y,e[k].w=w,e[k].next=head[x],head[x]=k++;
        e[k].x=y,e[k].x=x,e[k].w=w,e[k].next=head[y],head[y]=k++;
    }
    
    void init(int n,int m)
    {
        memset(e,0,sizeof(e));
        for(int i=0;i<n;i++)
        {
            head[i]=-1,vis[i]=0,dis[i]=0x3f3f3f3f;
        }
        for(int i=0;i<2*m;i+=2)
        {
            int x,y,w;
            scanf("%d%d%d",&x,&y,&w);
            addedge(x,y,w,i);
        }
    }
    
    int SPFA(int src)
    {
        memset(cnt,0,sizeof(cnt));
        queue<int>q;
        vis[src]=1;
        dis[src]=0;
        cnt[src]++;
        q.push(src);
        while(!q.empty())
        {
            int u,v;
            u=q.front();
            q.pop();
            vis[u]=0;
            for(int i=head[u];i!=-1;i=e[i].next)
            {
                v=e[i].y;
                if(dis[v]>dis[u]+e[i].w){
                    dis[v]=dis[u]+e[i].w;
                    if(!vis[v]){
                        q.push(v);
                        vis[v]=1;
                    }
                }
            }
        }
    }
    int main()
    {
        int n,m,i,j,x,y;
        while(~scanf("%d%d",&n,&m))
        {
            init(n,m);
            scanf("%d%d",&x,&y);
            SPFA(x);
            printf("%d
    ",dis[y]==0x3f3f3f3f?-1:dis[y]);
        }
        return 0;
    }
    


  • 相关阅读:
    BZOJ4569: [Scoi2016]萌萌哒
    BZOJ4566: [Haoi2016]找相同字符
    BZOJ4556: [Tjoi2016&Heoi2016]字符串
    BZOJ4545: DQS的trie
    BZOJ4458: GTY的OJ
    Codeforces Beta Round #19E. Fairy
    不确定性推理
    朴素贝叶斯
    对抗搜索
    struct
  • 原文地址:https://www.cnblogs.com/wlxtuacm/p/5712282.html
Copyright © 2011-2022 走看看