一个问题
查看原帖
一个问题
368777
E9BE99E8888CE585B0楼主2020/9/12 22:01

我们教练自创了一个判负环的算法,时间复杂度算不出来(而且加了剪枝,算出来了也不一定准),但是他说这个算法的效率可以远超 SPFASPFA,我拿它去做了一下UVA558,还挺快的,二十来毫秒,但在这题的7 、8 、9 、10这几个点T掉了,请问这个算法的效率到底怎么样,在什么时候会比较快,什么时候会比较慢,能不能再优化。代码如下:

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstring>
using namespace std;
inline int read(){
	int w = 1, data = 0; char ch = 0;
	while(ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
	if(ch == '-') w = -1, ch = getchar();
	while(ch >= '0' && ch <= '9') data = data * 10 + ch - '0', ch = getchar();
	return w * data;
}
int T,n,m,flag,b[2010],start,t;
int cnt,head[2010];
struct Edge
{
	int to,next,w;
}edge[30010];
void add(int u,int v,int w){
	edge[cnt].to=v;
	edge[cnt].w=w;
	edge[cnt].next=head[u];
	head[u]=cnt++;
}
void dfs(int x,int s)
{
	if(t&&x==start)flag=1;
	if(flag)return;
	t=1;
	for(register int i=head[x];i!=-1;i=edge[i].next)
	{
		int v=edge[i].to;
		if(b[v]||s+edge[i].w>=0)continue;
		b[v]=1;
		dfs(v,s+edge[i].w);
		b[v]=0;
	}
}
int main()
{
	T=read();
	while(T--)
	{
		cnt=0;
		memset(head,-1,sizeof(head));
		flag=0;
		n=read();
		m=read();
		for(register int i=1;i<=m;++i)
		{
			int u,v,p;
			u=read();
			v=read();
			p=read();
			add(u,v,p);
			if(p>=0)
				add(v,u,p);
		}
		for(register int i=1;i<=n;++i)
		{
			t=0;
			start=i;
			dfs(i,0);
			if(flag)break;
		}
		if(flag) printf("YES\n");
		else printf("NO\n");
	}
	return 0;
}
2020/9/12 22:01
加载中...