【最短路】SPFA模板:最短路和判断负环

题目

LP3371
LP3385

思路

对于判断负环,当从起点到当前结点经过结点数大于n-1,跳出即可。

代码

单源最短路

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define _for(i,a,b) for(int i = a; i
#define _rep(i,a,b) for(int i = a; i<=b; i++)
using namespace std;

const int INF = 2147483647;
const int maxn = 10000+100;
struct edge{
    int u,v,w;
    edge(int u, int v, int w):u(u),v(v),w(w){}
};

int n, m, start, d[maxn];
bool inq[maxn];
vector edges;
vector<int> G[maxn];

void spfa(){
    queue<int> q;
    q.push(start);
    inq[start] = true;
    while(!q.empty()){
        int now = q.front();
        q.pop();
        inq[now] = false;
        _for(i,0,G[now].size()){
            int to = edges[G[now][i]].v, ww = edges[G[now][i]].w;
            if (d[to] > d[now] + ww){
                d[to] = d[now]+ww;
                if(!inq[to]) q.push(to);
                inq[to] = true;
            }
        }
    }
}

int main(){
    scanf("%d%d%d",&n,&m,&start);
    int u,v,w;
    _for(i,0,m){
        scanf("%d%d%d",&u,&v,&w);
        G[u].push_back(edges.size());
        edges.push_back(edge(u,v,w));
    }
    _rep(i,1,n) d[i] = INF;
    d[start] = 0;
    spfa();
    _rep(i,1,n) printf("%d ",d[i]);

    return 0;
}

判断负环
(YES5和N0是真的强)

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define _for(i,a,b) for(int i = a; i
#define _rep(i,a,b) for(int i = a; i<=b; i++)
using namespace std;

const int INF = 10000000;
const int maxn = 2000+100;
struct edge{
    int u,v,w;
    edge(int u, int v, int w):u(u),v(v),w(w){}
};

int n, m, start, d[maxn], cc[maxn];
bool inq[maxn];
vector edges;
vector<int> G[maxn];

bool spfa(){
    queue<int> q;
    q.push(start);
    inq[start] = true;
    while(!q.empty()){
        int now = q.front();
        q.pop();
        inq[now] = false;
        _for(i,0,G[now].size()){
            int to = edges[G[now][i]].v, ww = edges[G[now][i]].w;
            if (d[to] > d[now] + ww){
                d[to] = d[now]+ww;
                cc[to] = cc[now]+1;
                if (cc[to] > n-1) return false;
                if(!inq[to]) q.push(to);
                inq[to] = true;
            }
        }
    }
    return true;
}

int main(){
    //freopen("output.txt","w",stdout);
    int T;
    scanf("%d",&T);
    while(T--){
        memset(cc,0,sizeof(cc));
        memset(inq,0,sizeof(inq));
        scanf("%d%d",&n,&m);
        start = 1;
        _rep(i,1,n) G[i].clear();
        edges.clear();
        int u,v,w;
        _for(i,0,m){
            scanf("%d%d%d",&u,&v,&w);
            G[u].push_back(edges.size());
            edges.push_back(edge(u,v,w));
            if (w >= 0){
                G[v].push_back(edges.size());
                edges.push_back(edge(v,u,w));
            }
        }
        _rep(i,1,n) d[i] = INF;
        d[start] = 0;
        if (spfa()) printf("N0\n");
        else printf("YE5\n");   
    }

    return 0;
}

你可能感兴趣的:(9.noip及时复习)