Codeforces Round #743 (Div. 2)C.book
#include "bits/stdc++.h"
using namespace std;
const int maxn = 3e5 + 10;
int k[maxn];
vector<int> v[maxn];
int du[maxn];
vector<int> arr;
set<int> q, p;
int main() {
int t;
cin >> t;
while(t--) {
q.clear();
p.clear();
int n;
cin >> n;
arr.clear();
for (int i = 1; i <= n; i++)
{
du[i] = 0;
v[i].clear();
}
for (int i = 1; i <= n; i++) {
cin >> k[i]; du[i] = k[i];
for (int j = 1; j <= k[i]; j++)
{
int x;
cin >> x;
v[x].push_back(i);
}
}
for (int i = 1; i <= n; i++) {
if (du[i] == 0) {
q.insert(i);
}
}
int ans = 0;
while (!q.empty() || !p.empty()) {
ans++;
for (auto u : q) {
arr.push_back(u);
for (int j = 0; j < v[u].size(); j++) {
du[v[u][j]]--;
if (du[v[u][j]] == 0) {
if (v[u][j] < u)
p.insert(v[u][j]);
else
q.insert(v[u][j]);
}
}
}
q = p;
p.clear();
}
if (arr.size() != n)
cout << -1 << endl;
else
cout << ans << endl;
}
return 0;
}