CF1931F 题解

· · 题解

Solution

好题。

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

Implementation

#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;
}