跳到正文

题解

CF1931F 题解

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

文章信息

发布
2025年7月27日
收录
2025年12月12日
更新
2026年8月29日
篇幅
约 2 分钟
题目
CF1931F

版本

  1. v1当前

Solution

好题。

虽然观众视角下无非直接确定完整的顺序,但是可以得到一部分残缺的顺序,当 i≥2i \ge 2 时,我们可以得到 ai−1a_{i-1} 一定在 aia_i 前面。所以,直接建图跑拓扑排序,看看有没有环即可。

Implementation

C++
#include <bits/stdc++.h>

using namespace std;

#define int long long
#define PII pair<int, int>
#define VI vector<int>
#define sz(a) a.size()
#define all(a) a.begin(), a.end()
#define up(i, s, t) for (int i = s; i <= t; i++)
#define dw(i, s, t) for (int i = s; i >= t; i--)

signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	
	int t, n, k; cin >> t;
	while (t-- && cin >> n >> k) {
		vector<VI> g(n + 1);
		VI in(n + 1);
		if (n == 1) {
			up(i, 1, n) {
				int x; cin >> x;
			}
			cout << "YES\n";
			continue;
		}
		up(i, 1, k) {
			int x, last, cnt = 0;
			cin >> x >> last;
			up(j, 2, n - 1)
				cin >> x, g[last].push_back(x), 
				in[x]++, last = x, cnt++;
		}
		queue<int> q;
		int cnt = 0;
		up(i, 1, n) if (!in[i]) q.push(i), cnt++;
		while (q.size()) {
			int u = q.front();
			q.pop();
			for (int v : g[u]) 
				if (--in[v] == 0)
					q.push(v), cnt++;
		}
		if (cnt == n) cout << "YES\n";
		else cout << "NO\n";
	}
	return 0;
}
原文