HDU 3259 Wormholes

来源:互联网 发布:淘宝采购 开具什么发票 编辑:程序博客网 时间:2024/06/14 15:53

题意:就是给你一个n,m,t   n代表有多少个点,m代表有多少个双向的边  t代表的是虫洞,现在要你判读是否还可以穿越到过去的点

虫洞的意思是给你的边是单向的,并且是负权值(输入的时候是正数)




思路:是否可以穿越回过去的点,即有没有负环,果断套用模板,dijkstra算法不能检测负环

AC代码:

#include<cstdio>#include<cstring>#include<iostream>#include<queue>#include<algorithm>#include<vector>using namespace std;#define maxn 520const int INF = 0x3fffffff;struct Edge{    int from,to,dist;};struct BellmanFord{    int n,m;    vector<Edge> edges;    vector<int> G[maxn];    bool inq[maxn];    int d[maxn];    int p[maxn];    int cnt[maxn];    Edge e;    void init(int n)    {        this->n=n;        for(int i=0;i<n;i++)            G[i].clear();        edges.clear();    }    void AddEdge(int from,int to,int dist)    {        edges.push_back((Edge){from,to,dist});        m=edges.size();        G[from].push_back(m-1);    }    bool negativeCycle()    {        queue<int >Q;        memset(inq,0,sizeof(inq));        memset(cnt,0,sizeof(cnt));        for(int i=0;i<n;i++)        {            d[i]=INF;            inq[0]=true;            Q.push(i);        }        d[0] = 0;        while(!Q.empty())        {            int u=Q.front();            Q.pop();            inq[u]=false;            for(int i=0;i<G[u].size();i++)            {                Edge& e=edges[G[u][i]];                if(d[e.to]>d[u]+e.dist)                {                    d[e.to]=d[u]+e.dist;                    p[e.to]=G[u][i];                    if(!inq[e.to])                    {                        Q.push(e.to);                        inq[e.to]=true;                        if(++cnt[e.to]>n)                            return true;                    }                }            }        }        return false;    }};int main(){     int a,b,c,i,node,m,t,case1,k;     bool j;     scanf("%d",&case1);     while(case1--)     {            scanf("%d %d %d",&node,&m,&t);            if(node==0&&m==0)break;            BellmanFord tu;            tu.init(node);            for(i=0;i<m;i++)            {                scanf("%d %d %d",&a,&b,&c);                a--;b--;                tu.AddEdge(a,b,c);                tu.AddEdge(b,a,c);            }            for(k=0;k<t;k++)            {                scanf("%d %d %d",&a,&b,&c);                a--;                b--;                tu.AddEdge(a,b,-c);            }            j=tu.negativeCycle();            if(j)                printf("YES\n");            else                printf("NO\n");     }     return 0;}


0 0
原创粉丝点击