CodeForces - 915D Almost Acyclic Graph
阿新 • • 發佈:2020-08-23
\(\text{Solution}\)
最近複習縮點,一看到這道題就想預處理出所有強連通分量,然後判斷是否所有的強連通分量只共用一條邊(話說這和判環有什麼關係)。
考慮到 \(n\) 的範圍非常小,題目中只要刪一條邊,在拓撲排序中刪除到 \(u\) 的邊實際上是將其入度減一。我們可以列舉點,對每個刪除的點拓撲一遍。總時間複雜度 \(\mathcal{O(n\times (n+m))}\)。
\(\text{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; }