poj 3259 Wormholes

这是一道求有没有负环的题,用到bellman算法;

这里要注意的是路是双向的;

View Code
#include<iostream>

#include<cstdio>

#include<cstdlib>

#include<algorithm>

#include<cmath>

using namespace std;

class Weight

{

public:

      int S,E,T;

}edge[5024];

bool Bell_man( int count, int N )

{

    int dis[1024] = {0},flag = 0;

    for( int i = 0 ; i < N -1 ; i ++ )

    {

        flag = 0;

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

           {

            if( dis[edge[j].E] > dis[edge[j].S] + edge[j].T )

            {

                dis[edge[j].E] = dis[edge[j].S] + edge[j].T;    

                flag = 1;

            }        

        }

        if( !flag ) break;

    }    

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

    {

       if( dis[edge[i].E] > dis[edge[i].S] + edge[i].T )

         return true;       

    }

    return false;

}

int main()

{

    int Case,N,M,W,S,T,E;

    while( scanf( "%d",&Case )==1 )

    {

       while( Case-- )

       {

          int count = 0;

          scanf( "%d %d %d",&N,&M,&W );

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

          {

               scanf( "%d %d %d",&S,&E,&T );

               edge[count].S = edge[count+1].E = S;

               edge[count+1].S = edge[count].E = E;

               edge[count].T = edge[count+1].T = T; count+=2;        

          }        

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

          {

              scanf( "%d %d %d",&S,&E,&T );

              edge[count].S = S ; edge[count].E= E;

              edge[count].T = -T ; count++;        

          }

          if( Bell_man( count ,N ) )

             printf( "YES\n" );

          else printf( "NO\n" );

       }    

    }

   return 0;    

}

 

你可能感兴趣的:(orm)