UVA 558 判断负环 By ACReaper

哎,好久没切题了,今天又来切题鸟,一定要坚持!!!至少每天一题!

这题本质就是判断图中有没有负环。我的第一反应就是用Bellman-ford算法解决,代码如下


#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
typedef pair<int,int> pii;
const int maxn = 1006;
const int INF = 0x2fffffff;
vector<pii> G[maxn];
int d[maxn];
int main()
{
    int t,n,m;
    int len_adj = -1;
    bool tag_haveWormHole = false;
    scanf("%d",&t);
    
    for(int i = 1; i <= t; i++){
	  //pre process start
	  len_adj = -1;
      tag_haveWormHole = false;
      for(int j = 0; j < maxn; j++)
		 d[j] = INF;
      d[0] = 0;
      for(int j = 0; j < maxn; j++)
         G[j].clear();
	  //pre process end
      scanf("%d%d",&n,&m);
      for(int j = 0; j < m; j++){//Build Adj Graph
         int u,v,w;
         scanf("%d%d%d",&u,&v,&w);
         G[u].push_back(make_pair(v,w));
	     if(u > len_adj)
            len_adj = u;
      }
      
      //Bellford-man-algorithm
      for(int i1 = 1; i1 <= n - 1; i1++){
		for(int j = 0; j <= len_adj; j++){//哎,len_adj因是adj的最大的下标不是大小!,在这坑了
	      for(int k = 0; k < G[j].size(); k++){
				int u = j;
                int v = G[j][k].first;
                int w = G[j][k].second;
	//			printf("v = %d,u = %d, w = %d,d[v] = %d\n",v,u,w,d[v]);
                if(d[v] > d[u] + w){
				  d[v] = d[u] + w;
			//	  printf("d[%d] = %d ",v,d[v]); 
				} 
			}
		 }
//		printf("#%d end\n",i1);
	
	 }
	 // puts("");
	  //output test
	  
	  //for(int i1 = 0; i1 < 5 ;i1++)
		//  printf("d[%d] = %d ",i1,d[i1]);
 //     puts("");

	  //output test end
    for(int j = 0; j < len_adj;j++){
	for(int k = 0; k < G[j].size(); k++){
		   int u = j;
           int v = G[j][k].first;
           int w = G[j][k].second;
           if(d[v] >d[u] + w){
           	tag_haveWormHole = true;
             }
      	}
    } 
   if(tag_haveWormHole)
	 puts("possible");
   else
	puts("not possible");
  }
    return 0;
}
2013 05 30

By ACReaper

posted @ 2013-05-30 23:50  算法黑魔王  阅读(139)  评论(0编辑  收藏  举报