POJ:3259 Wormholes(SPFA判断负环)

这个题最坑爹的地方在于有重边,因此有邻接矩阵比较方便。

所以无向图的时候要这样

if(w

而无向图

  gl[u][v]=-w;

#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int gl[505][505];
        memset(gl,0x7f,sizeof(gl));
        int INF=gl[0][0];
        int N,M,W;
        scanf("%d%d%d",&N,&M,&W);
        int u,v,w;
        for(int i=0; i q;
        q.push(1);
        cou[1]++;
        inq[1]=true;
        bool yes=false;
        while(!q.empty())
        {
            int tmp=q.front();
            q.pop();
            if(cou[tmp]>N)
            {
                yes=true;
                break;
            }
            for(int i=1; i<=N; ++i)
            {
                if(gl[tmp][i]!=INF&&gl[tmp][i]+dist[tmp]


 

下面这个是用邻接表实现的,处理重边的时候就比较麻烦了。。

#include
#include
#include
#include
#include
#include
using namespace std;
struct Edge
{
    int from,to,cost;
    Edge(int a,int b,int c):from(a),to(b),cost(c) {}
};
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int N,M,W;
        scanf("%d%d%d",&N,&M,&W);
        int u,v,w;
        vector adjlist[505];
        for(int i=0; iw)
                {
                    adjlist[u][k].cost=w;
                    for(int j=0; jw)
                        {
                            adjlist[v][j].cost=w;
                            break;
                        }
                    }
                    ok=true;
                    break;
                }
            }
            if(!ok)
            {
                adjlist[u].push_back(Edge(u,v,w));
                adjlist[v].push_back(Edge(v,u,w));
            }
        }
        for(int i=0; i q;
        int dist[505],cou[505]= {0};
        bool inq[505]= {0};
        memset(dist,0x7f,sizeof(dist));
        dist[1]=0;
        q.push(1);
        inq[1]=true;
        cou[1]++;
        bool yes=false;
        while(!q.empty())
        {
            int tmp=q.front();
            if(cou[tmp]>N)
            {
                yes=true;
                break;
            }

            for(int i=0; idist[tmp]+adjlist[tmp][i].cost)
                {

                    dist[v]=dist[tmp]+adjlist[tmp][i].cost;
                    if(!inq[v])
                    {
                        q.push(v);
                        inq[v]=true;
                        cou[v]++;
                    }
                }
            }
            inq[tmp]=false;
            q.pop();
        }
        if(yes) puts("YES");
        else puts("NO");
    }
    return 0;
}


 

 

你可能感兴趣的:(POJ)