关于SPFA判松弛次数求负环的正确性
查看原帖
关于SPFA判松弛次数求负环的正确性
105833
樱洛CHANGE楼主2021/8/27 06:33

题解中普遍说,SPFA只能通过判断入队次数来判断负环,判断松弛次数不具有正确性,但是蒟蒻却用判断松弛次数的SPFA过掉了Hack数据,请问蒟蒻的程序是完全正确不会被Hack的吗。

代码:

#include<bits/stdc++.h>
#define awa 2147483647
#define zhale exit(0)
#define re register
#define rint re int

using namespace std;
/*Shioiri Kukuri*/

typedef long long ll;
typedef unsigned long long ull;
typedef double qwq;
typedef pair<int,int> P;
typedef pair<ll,ll> llP;
#define rll re ll
#define rqwq re qwq

/*Otho Ai*/

template<class T>
void Swap(T &x,T &y)
{
	T z=x;
	x=y;
	y=z;
}

//#define PairOP
#ifdef PairOP
template<class T1,class T2>
inline const pair<T1,T2> operator + (const pair<T1,T2> &p1,const pair<T1,T2> &p2){
	return pair<T1,T2>(p1.first+p2.first,p1.second+p2.second);
}

template<class T1,class T2>
inline const pair<T1,T2> operator - (const pair<T1,T2> &p1,const pair<T1,T2> &p2){
	return pair<T1,T2>(p1.first-p2.first,p1.second-p2.second);
}
#endif

//#define FastIO
#ifdef FastIO
	char buf[1<<21],*p1,*p2;
	#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
#endif

template<class T>
T Read()
{
	T x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9')
	{
		if(ch=='-')
		f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9')
	{
		x=(x<<1)+(x<<3)+(ch^'0');
		ch=getchar();
	}
	return x*f;
}
//int (*read)()=Read<int>;
ll (*readll)()=Read<ll>;
#define read Read<int>

const int N=3e3+5;
int t,n,m,tot,head[N],ver[N<<1],edge[N<<1],nxt[N<<1];

inline void add(rint x,rint y,rint z)
{
	ver[++tot]=y;
	edge[tot]=z;
	nxt[tot]=head[x];
	head[x]=tot;
}

int d[N],cnt[N];
bool v[N];
queue<int>q;
bool spfa()
{
	memset(d,0x3f,sizeof(d));
	memset(v,0,sizeof(v));
	memset(cnt,0,sizeof(cnt));
	while(!q.empty()) q.pop();
	d[1]=0,q.push(1),v[1]=1;
	while(!q.empty())
	{
		int x=q.front();
		q.pop();
		v[x]=0;
		for(int i=head[x];i;i=nxt[i])
		{
			int y=ver[i],z=edge[i];
			if(d[y]>d[x]+z)
			{
				d[y]=d[x]+z,cnt[y]=cnt[x]+1;
				if(cnt[y]>=n) return 1;//判断松弛次数
				if(!v[y]) v[y]=1,q.push(y);
			}
		}
	}
	return 0;
}
inline int True()
{
//#define Freopen
#ifdef Freopen
	freopen(".in","r",stdin);
	freopen(".out","w",stdout);
#endif

//#define Clock
#ifdef Clock
	rint STR=clock();
#endif

	t=read();
	while(t--)
	{
		n=read(),m=read();
		memset(ver,0,sizeof(ver));
		memset(head,0,sizeof(head));
		memset(edge,0,sizeof(edge));
		memset(nxt,0,sizeof(nxt));
		while(!q.empty())q.pop();
		tot=0;
		for(rint i=1;i<=m;++i)
		{
			rint x=read(),y=read(),z=read();
			if(z>=0) add(x,y,z),add(y,x,z);
			else add(x,y,z);
		}
		puts(spfa()?"YES":"NO");
	}

#ifdef Clock
	rint END=clock();
	printf("Time:%dms\n",int((END-STR)/(qwq)CLOCKS_PER_SEC*1000));
	printf("Time:%ds\n",int((END-STR)/(qwq)CLOCKS_PER_SEC));
#endif
	return (0-0);//q(0-0)p q(>-<)p
}

int Love=True();

signed main(){;}

2021/8/27 06:33
加载中...