abc315E 解锁1号图书要读的最少书

有n本书,编号分别为1~n。在读第i本书之前需要先读c[i]本书,编号分别为p[i][1],p[i][2],...p[i][c[i]]。现想读1号书,需要提前读至少多少本书,输出任意一组方案。
2<=n<=2E5; 0<=c[i]<n,保证有解。

类似求拓扑序,由于要输出方案,用dfs更方便。另外题目保证有解,不需要判环。

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,a,b) for(int i=a; i<=b; i++)
#define per(i,a,b) for(int i=b; i>=a; i--)

const int Z = 200005;
int n, vis[Z];
vector<int> adj[Z];
int dfs(int x) {
    vis[x] = -1;
    for (auto i : adj[x]) if (vis[i] == 0) {
        dfs(i);
    }
    vis[x] = 1;
    if (x != 1) cout << x << " ";
    return 0;
}
void solve() {
    cin >> n;
    rep(i,1,n) {
        int c, p;
        cin >> c;
        rep(j,1,c) {
            cin >> p;
            adj[i].push_back(p);
        }
    }
    dfs(1);
}

signed main() {
    cin.tie(0)->sync_with_stdio(0);
    int t = 1;
    while (t--) solve();
    return 0;
}
posted @ 2024-03-11 21:22  chenfy27  阅读(2)  评论(0编辑  收藏  举报