Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

DFS版spfa 写丑了? 为啥比bfs spfa慢好多

Posted by dong_123 at 2013-03-14 10:43:44 on Problem 3259
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define inf 200000000
using namespace std;
typedef struct{
	int y,next,w;
}node;
node g[60000];
int v[6000],d[6000],a[6000];
int n,m,w,tot,flag;
void Add(int u,int v,int w){
	g[++tot].y=v;g[tot].w=w;
	g[tot].next=a[u];a[u]=tot;
}
void Init(){
	int x,y,z;
	
	tot=0;
	memset(a,0,sizeof(a));
	for(int i=1;i<=m+w;i++){
		scanf("%d %d %d",&x,&y,&z);
		if(i<=m){
		//printf("%d %d %d\n",x,y,z);
		Add(x,y,z);
		Add(y,x,z);
		}else Add(x,y,-z);
	}
}
void Dfs(int k){
	int now;
	if(flag) return;
	v[k]=1;
	//printf("%d\n",k);
	for(int s=a[k];s;s=g[s].next){
		now=g[s].y;
		if(d[now]>d[k]+g[s].w){
			d[now]=d[k]+g[s].w;
			if(v[now]&&!flag){
				printf("YES\n");
				flag=1;
			}else{
				v[now]=1;
				Dfs(now);
			}
		}
	}
	v[k]=0;
}
void Spfa(){
	memset(v,0,sizeof(v));
	for(int i=2;i<=n;i++) d[i]=inf;
	d[1]=0;
	Dfs(1);
}
int main(){
	int T;
	freopen("test.in","r",stdin);
	scanf("%d",&T);
	while(cin>>n>>m>>w){
		flag=0;
		Init();
		Spfa();
		if(!flag) printf("NO\n");
	}
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator