poj 3259Wormholes (spfa最短路径)

#include<stdio.h>

#include<string.h>

#include<limits.h>

#include<queue>

using namespace std;

#define N 5505

#define M 55000//注意边和点集的数组大小

struct edge

{

    int to,value,next;

}edges[M];

int heads[N],len=0;

int addedge(int u,int v,int w)

{

    edges[len].to=v,edges[len].value=w,edges[len].next=heads[u];

    heads[u]=len++;

    return 0;

}

int n,m;



int spfa(int v)

{

    queue<int> q;

    int inqueue[N],dis[N];

    memset(inqueue,0,sizeof(inqueue)),inqueue[v]=1;

    q.push(v);

    for(int i=0;i<n;i++) dis[i]=INT_MAX;

    dis[v]=0;

    int times[N];

    memset(times,0,sizeof(times)),times[v]=1;



    while(!q.empty()){

        int x=q.front();

        q.pop();

        inqueue[x]=0;

        for(int j=heads[x];j!=-1;j=edges[j].next){

            int to=edges[j].to,value=edges[j].value;

            if(value+dis[x]<dis[to]){

                dis[to]=value+dis[x];

                if(!inqueue[to]){  //注意已经在队列里面的不用再加入队列

                    if(++times[to]>=n) return 0;

                    inqueue[to]=1,q.push(to);

                }

            }

        }

    }

    return 1;

}

int main(void)

{

    int i,j,t;

    int a,b,c;

    scanf("%d",&t);

    while(t--){

        int w;

        memset(heads,-1,sizeof(heads));//注意不要忘记

        scanf("%d%d%d",&n,&m,&w);

        while(m--){

            scanf("%d%d%d",&a,&b,&c);

            addedge(a-1,b-1,c);

            addedge(b-1,a-1,c);

        

        }

        while(w--){

            scanf("%d%d%d",&a,&b,&c);

            addedge(a-1,b-1,-c);

        }

        if(!spfa(0)) printf("YES\n");

        else printf("NO\n");

    }

    

}

你可能感兴趣的:(最短路径)