跳到正文

题解

题解:P8405 [COCI 2021/2022 #6] Naboj

jensonljs约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年4月30日
收录
2026年5月5日
更新
2026年11月10日
篇幅
约 2 分钟
题目
P8405

版本

  1. v2当前
  2. v1

题解:P8405 [COCI 2021/2022 #6] Naboj

思路

拓扑排序板子题。观察题目,注意到按拓扑序给金属球充负电荷也是一种可行解,所以我们反着建图,使电子更靠近每条边的终点,然后从入度为 00 的点开始进行拓扑排序。如果图中存在环,则不存在可行解,输出 −1-1。

AC Code

C++
#include<bits/stdc++.h>
#define rg register
using namespace std;
const int N = 2e5 + 1, M = 5e5 + 1;
struct edge {
	int to, nxt;
} e[M];
int h[N], cnt, n, m, in[N], sum;
queue<int> q;
vector<int> ans;
inline void add(int u, int v){
	e[++cnt].to = v;
	e[cnt].nxt = h[u];
	h[u] = cnt;
	return;
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m;
	for (rg int i = 1; i <= m; i++) {
		int u, v;
		cin >> u >> v;
		add(v, u); // 建反图
		in[u]++;
	}
	for (rg int i = 1; i <= n; i++) {
		if (!in[i]) {
			q.emplace(i);
		}
	}
	while (q.size()) { // 拓扑排序
		rg int u = q.front();
		q.pop();
		sum++;
		for (rg int i = h[u]; i; i = e[i].nxt) {
			rg int v = e[i].to;
			in[v]--;
			if (!in[v]) {
				q.emplace(v);
				ans.push_back(v);
			}
		}
	}
	if (sum != n) cout << -1, exit(0); // 存在环
	cout << ans.size() << '\n';
	for (int it : ans) cout << it << " 1\n";
	return 0;
}
原文