poj 3259 Wormholes(spfa)

#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
const int inf=0x3f3f3f3f;
const int N=1024;

struct node
{
    int to;
    int w;
    node *next;
};

node* edge[N];
int n,m,w,cnt[N],vis[N],dist[N];
queue<int>q;

int spfa(int v0)
{
    while(!q.empty()) q.pop();
    int i,u;
    node *ptr;
    for(i=1; i<N; i++)
    {
        dist[i]=inf;
        vis[i]=0;
        cnt[i]=0;
    }
    dist[v0]=0;
    vis[v0]=1;
    q.push(v0);
    cnt[v0]++;
    while(!q.empty())
    {
        u=q.front();
        q.pop();
        vis[u]=0;
        if(cnt[u]>n) return 1;
        ptr=edge[u];
        while(ptr!=NULL)
        {
            if(dist[ptr->to]>dist[u]+ptr->w)
            {
                dist[ptr->to]=dist[u]+ptr->w;
                if(vis[ptr->to]==0)
                {
                    vis[ptr->to]=1;
                    cnt[ptr->to]++;
                    q.push(ptr->to);
                }
            }
            ptr=ptr->next;
        }
    }
    return 0;
}

int main()
{
    int _,i,u,v,t,flag;
    node* temp;
    scanf("%d",&_);
    while(_--)
    {
        scanf("%d%d%d",&n,&m,&w);
        for(i=1; i<N; i++)
            edge[i]=NULL;

        for(i=0; i<m; i++)
        {
            scanf("%d%d%d",&u,&v,&t);
            temp=new node;
            temp->to=v;
            temp->w=t;
            temp->next=NULL;
            if(edge[u]==NULL)
            {
                edge[u]=temp;
            }
            else
            {
                temp->next=edge[u];
                edge[u]=temp;
            }

            temp=new node;
            temp->to=u;
            temp->w=t;
            temp->next=NULL;
            if(edge[v]==NULL)
            {
                edge[v]=temp;
            }
            else
            {
                temp->next=edge[v];
                edge[v]=temp;
            }

        }
        for(i=0; i<w; i++)
        {
            scanf("%d%d%d",&u,&v,&t);
            temp=new node;
            temp->to=v;
            temp->w=-t;
            temp->next=NULL;
            if(edge[u]==NULL)
            {
                edge[u]=temp;
            }
            else
            {
                temp->next=edge[u];
                edge[u]=temp;
            }
        }
        flag=spfa(1);
        if(flag) printf("YES
");
        else printf("NO
");
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

原文地址:https://www.cnblogs.com/xryz/p/4847954.html