Codeforces Round #656 (Div. 3) E. Directing Edges

Posted TURNINING

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces Round #656 (Div. 3) E. Directing Edges相关的知识,希望对你有一定的参考价值。

传送门

题意:一个图,给你n个顶点,m条边,m条边中有些是有向的,有些是无向的。现在要求你把无向的边全部变成有向的边,能否使图最终无环?

思路:先只看有向边,若原图已经有环那么肯定无解,若无环我们一定能通过拓扑序构造一个图使图无环。

证明:先跑一个拓扑排序,对于一个无向的边,我们只要把边:从拓扑序小的指向拓扑序大的 就能保正不产生环(拓扑序的定义!)

#include<bits/stdc++.h>
using namespace std;

#define lsn (u << 1)
#define rsn (u << 1 | 1)
#define mid (l + r >> 1)

typedef long long ll;
typedef unsigned long long ull;

typedef pair<int, int> P;

const int MAXN = 2e5 + 10;
const int MAX_LEN = 100000 + 10;
const int MAX_LOG_V = 22;
const int INF = 1e6;
const int mod = 1e9 + 7;
const double eps = 1e-7;
const ull B = 100000007;


int n, m, no[MAXN], d[MAXN];
vector<int> g[MAXN];
P f[MAXN];


void solve() {
	scanf("%d %d", &n, &m);
	for(int i = 1; i <= n; i++) { d[i] = 0; g[i].clear(); }
	for(int i = 1; i <= m; i++) {
		int op, u, v; scanf("%d %d %d", &op, &u, &v);
		f[i].first = u; f[i].second = v;
		if(op) {
			g[u].emplace_back(v);
			d[v]++;
		}
	}
	queue<int> q;
	for(int i = 1; i <= n; i++) {
		if(!d[i]) q.emplace(i); 
	}
	int tot = 0;
	while(!q.empty()) {
		int u = q.front(); q.pop();
		no[u] = ++tot;
		for(int i = 0; i < g[u].size(); i++) {
			int v = g[u][i];
			d[v]--;
			if(!d[v]) q.emplace(v);
		}
	}
	if(tot != n) puts("NO");
	else {
		puts("YES");
		//printf("YES\\n");
		for(int i = 1; i <= m; i++) {
			if(no[f[i].first] < no[f[i].second]) printf("%d %d\\n", f[i].first, f[i].second);
			else printf("%d %d\\n", f[i].second, f[i].first);
		}	
	}
}

int main() {
	int t = 1; scanf("%d", &t);
	while(t--) { 
		solve();
	}
}

以上是关于Codeforces Round #656 (Div. 3) E. Directing Edges的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #656 (Div. 3)

Codeforces Round #656 (Div. 3) A. Three Pairwise Maximums(思维/构造)

Codeforces Round #656 (Div. 3) E. Directing Edges

Codeforces Round #656 (Div. 3) E. Directing Edges

Codeforces Round #656 (Div. 3) E. Directing Edges

Codeforces Round #656 (Div. 3)E. Directing Edges(拓扑排序+构造dag图)