1. 程式人生 > >Almost Acyclic Graph CodeForces - 915D (思維,圖論)

Almost Acyclic Graph CodeForces - 915D (思維,圖論)

empty ++i mes return cto name 復雜度 tdi %d

大意: 給定無向圖, 求是否能刪除一條邊後使圖無環

直接枚舉邊判環復雜度過大, 實際上刪除一條邊可以看做將該邊從一個頂點上拿開, 直接枚舉頂點即可

復雜度$O(n(n+m))$

#include <iostream>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <cstdio>
#include <queue>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define pb push_back
using namespace std;

const int N = 510;
int n, m, ok;
vector<int> g[N];
int vis[N], s[N], deg[N], a[N];


int topo() {
	queue<int> q;
	REP(i,1,n) if (!a[i]) q.push(i);
	int r = 0;
	while (!q.empty()) {
		++r;
		int x=q.front();q.pop();
		for (int y:g[x]) {
			if (!--a[y]) q.push(y);
		}
	}
	return r==n;
}

int main() {
	scanf("%d%d", &n, &m);                                                      
	REP(i,1,m) {
		int u, v;
		scanf("%d%d", &u, &v);
		g[u].pb(v),++deg[v];
	} 
	REP(i,1,n) if (deg[i]) {
		memcpy(a,deg,sizeof deg);
		--a[i];
		if (topo()) return puts("YES"),0;
	}
	puts("NO");
}

Almost Acyclic Graph CodeForces - 915D (思維,圖論)