poj 3259 Wormholes

和poj 1860差不多都用bellman—ford最简单的版本就可以了,关键在于巧妙的运用,做过了才能更好地理解》

#include<stdio.h>

#include<queue>

#include<string.h>

#define INF 100000000

#define MAXN1 520

#define MAXN 8000



int u[MAXN],v[MAXN],wt[MAXN], d[MAXN1];

int n, m, w, T,p;



void init()

{

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

    p = 0;

    for(int i = 0; i < m; i ++)

    {

        scanf("%d%d%d",&u[p],&v[p],&wt[p]);

        p++;

        u[p] = v[p-1];

        v[p] = u[p-1];

        wt[p] = wt[p-1];

        p++;

    }

    for(int i = m; i < m+w; i ++)

    {

        scanf("%d%d%d",&u[p],&v[p],&wt[p]);

        wt[p] = -wt[p];

        p++;

    }

}



void bellman_ford(int h)

{

    for(int i = 1; i <= n; i ++) d[i] = 0;

    d[h] = 0;

    for(int k = 0; k < n-1; k ++)

    for(int i = 0; i < p; i ++)

    {

        int x = u[i], y = v[i];

        if(d[x] < INF && d[y] > d[x] + wt[i])

        d[y] = d[x] + wt[i];

    }

}



int main()

{

    while(~scanf("%d",&T))

    {

        while(T --)

        {

            init();

            int ok = 0;

                bellman_ford(1);

                for(int j = 0; j < p; j ++)

                {

                    int x = u[j], y = v[j];

                    if(d[x] < INF && d[y] > d[x] + wt[j])

                    {ok = 1; break;}

                }

            if(ok == 1) printf("YES\n");

            else printf("NO\n");

        }

    }

    return 0;

}

你可能感兴趣的:(orm)