CodeForces

( ext{Solution})

最近复习缩点,一看到这道题就想预处理出所有强连通分量,然后判断是否所有的强连通分量只共用一条边(话说这和判环有什么关系)

考虑到 (n) 的范围非常小,题目中只要删一条边,在拓扑排序中删除到 (u) 的边实际上是将其入度减一。我们可以枚举点,对每个删除的点拓扑一遍。总时间复杂度 (mathcal{O(n imes (n+m))})

( ext{Code})

#include <cstdio>

#define rep(i,_l,_r) for(register signed i=(_l),_end=(_r);i<=_end;++i)
#define fep(i,_l,_r) for(register signed i=(_l),_end=(_r);i>=_end;--i)
#define erep(i,u) for(signed i=head[u],v=to[i];i;i=nxt[i],v=to[i])
#define efep(i,u) for(signed i=Head[u],v=to[i];i;i=nxt[i],v=to[i])
#define print(x,y) write(x),putchar(y)

template <class T> inline T read(const T sample) {
	T x=0; int f=1; char s;
	while((s=getchar())>'9'||s<'0') if(s=='-') f=-1;
	while(s>='0'&&s<='9') x=(x<<1)+(x<<3)+(s^48),s=getchar();
	return x*f;
}
template <class T> inline void write(const T x) {
	if(x<0) return (void) (putchar('-'),write(-x));
	if(x>9) write(x/10);
	putchar(x%10^48);
}
template <class T> inline T Max(const T x,const T y) {if(x>y) return x; return y;}
template <class T> inline T Min(const T x,const T y) {if(x<y) return x; return y;}
template <class T> inline T fab(const T x) {return x>0?x:-x;}
template <class T> inline T Gcd(const T x,const T y) {return y?Gcd(y,x%y):x;}
template <class T> inline T Swap(T &x,T &y) {x^=y^=x^=y;}

#include <queue>
using namespace std;

const int N=505,M=1e5+5;

int n,m,head[N],cnt,to[M],nxt[M],in[N],deg[N];
queue <int> q;

void addEdge(int u,int v) {
	nxt[++cnt]=head[u],to[cnt]=v,head[u]=cnt;
}

bool topol() {
	int tot=0;
	rep(i,1,n) in[i]=deg[i];
	rep(i,1,n) if(!in[i]) q.push(i);
	while(!q.empty()) {
		int u=q.front(); q.pop();
		++tot;
		erep(i,u) {
			--in[v];
			if(!in[v]) q.push(v);
		}
	}
	return tot==n;
}

int main() {
	int u,v; bool flag=0;
	n=read(9),m=read(9);
	rep(i,1,m) {
		u=read(9),v=read(9);
		addEdge(u,v); ++deg[v];
	}
	rep(i,1,n)	
		if(deg[i]) {
			--deg[i]; flag=1;
			if(topol()) return puts("YES"),0;
			++deg[i];
		}
	puts(flag?"NO":"YES");
	return 0;
} 
原文地址:https://www.cnblogs.com/AWhiteWall/p/13549300.html