Codeforces Round #743C Book(搜索)

#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;

int n;
vector<int>g[N];//读完i号书后可以解锁哪些书
int d[N];//一个书的前置数量
int f[N];//某本书读到第几轮才学会


void solve() {
    
    
	cin >> n;
	for (int i = 1; i <= n; i++)
		g[i].clear(), f[i] = 0, d[i] = 0;

	for (int i = 1; i <= n; i++) {
    
    
		int k;
		cin >> k;
		for (int j = 1; j <= k; j++) {
    
    
			int x;
			cin >> x;
			d[i]++;
			g[x].push_back(i);
		}
	}

	queue<int>q;
	for (int i = 1; i <= n; i++) {
    
    
		if (!d[i]) {
    
    
			q.push(i);
			f[i] = 1;
		}
	}
	while (!q.empty()) {
    
    
		int u = q.front();
		q.pop();
		for (auto i : g[u]) {
    
    
			d[i]--;
			if (i < u) {
    
     //当前点编号比待解锁编号大(要下一轮才能解锁)
				f[i] = max(f[i], f[u] + 1);
			} else {
    
    
				f[i] = max(f[i], f[u]);
			}
			if (!d[i])
				q.push(i);//第i本书学会了
		}
	}
	int ok = 0, ans = 0;
	for (int i = 1; i <= n; i++) {
    
    
		if (d[i])
			ok = 1;
		ans = max(ans, f[i]);
	}
	if (ok) {
    
    
		cout << "-1" << endl;
	} else {
    
    
		cout << ans << endl;
	}


}

signed main() {
    
    
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int t;
	cin >> t;
	while (t--) {
    
    
		solve();
	}
}

おすすめ

転載: blog.csdn.net/fdxgcw/article/details/120378083