poj3259 Wormholes --- spfa判負環

來源:互聯網
上載者:User

標籤:class   blog   code   ext   2014   string   

又寫了個bellman模板一直RE求解啊。。。


#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <cmath>#include <algorithm>#include <vector>#include <queue>#include <map>#define inf 0x3f3f3f3f#define ll __int64#define mod 1000000007using namespace std;struct node{    int v,w,next;}e[5300];int head[550],h,d[550],inq[550],outq[550],n,m,w;void init(){    memset(head,-1,sizeof head);    h=0;}void addedge(int a,int b,int c){    e[h].v=b;    e[h].w=c;    e[h].next=head[a];    head[a]=h++;}int spfa(int st){    memset(d,0x3f,sizeof d);    memset(inq,0,sizeof inq);    memset(outq,0,sizeof outq);    d[st]=0;inq[st]=1;    queue<int> q;    q.push(st);    while(!q.empty())    {        int x=q.front();        q.pop();        inq[x]=0;        outq[x]++;        if(outq[x]>n) return 0;//存在負環        for(int i=head[x];i!=-1;i=e[i].next)        {            if(d[e[i].v]>d[x]+e[i].w)            {                d[e[i].v]=d[x]+e[i].w;                if(!inq[e[i].v])                {                    inq[e[i].v]=1;                    q.push(e[i].v);                }            }        }    }    return 1;}int bellman(int st){    int i,j,k;    memset(d,0x3f,sizeof d);    d[st]=0;    for(i=0;i<n-1;i++)//n-1次鬆弛操作    {        for(j=0;j<n;j++)//枚舉每條邊        {            if(d[j]==inf) continue;            for(k=head[j];k!=-1;k=e[k].next)            {                if(e[k].w!=inf&&d[e[k].v]>d[j]+e[k].w)                    d[e[k].v]=d[j]+e[k].w;            }        }    }    for(j=0;j<n;j++)    {        if(d[j]==inf) continue;        for(k=head[j];k!=-1;k=e[k].next)        {            if(e[k].w!=inf&&d[e[k].v]>d[j]+e[k].w)                return 0;        }    }    return 1;}int main(){    int T,a,b,c;    scanf("%d",&T);    while(T--)    {        init();        scanf("%d%d%d",&n,&m,&w);        for(int i=0;i<m;i++)        {            scanf("%d%d%d",&a,&b,&c);            addedge(a,b,c);            addedge(b,a,c);        }        for(int i=0;i<w;i++)        {            scanf("%d%d%d",&a,&b,&c);            addedge(a,b,-c);        }        int ans=spfa(1);        if(!ans)            printf("YES\n");        else printf("NO\n");    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.