一道较简单的题。做法:拓扑排序+dp。
假设理解了第 u u u 章才能理解第 v v v 章,就连一条 u → v u\rightarrow v u→v 的单向边,接着直接拓扑求出符合要求的阅读顺序。
然后 dp 求答案。设 d p u dp_u dpu 表示按照拓扑序阅读到第 u u u 章的最小阅读次数。则:
if(v>u) dp[v]=max(dp[v],dp[u]);
else dp[v]=max(dp[v],dp[u]+1);
#include <bits/stdc++.h>
using namespace std;
//#define int long long
typedef long long ll;
typedef pair<int, int> pr;
#define up(i, l, r) for(int i = (l); i <= (r); i++)
#define down(i, r, l) for(int i = (r); i >= (l); i--)
const int mod = 1000000007;
const int base = 2333;
const double eps = 1e-6;
namespace fast_io {
char buf[1 << 12], *p1 = buf, *p2 = buf, sr[1 << 23], z[23], nc;
int C = -1, Z = 0, Bi = 0;
inline char gc() {
return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 12, stdin), p1 == p2) ? EOF : *p1++;
}
inline int read() {
int x = 0, y = 1;
while (nc = gc(), (nc < 48 || nc > 57) && nc != -1)if (nc == 45)y = -1;
Bi = 1;
x = nc - 48;
while (nc = gc(), 47 < nc && nc < 58)x = (x << 3) + (x << 1) + (nc ^ 48), Bi++;
return x * y;
}
inline void ot() {
fwrite(sr, 1, C + 1, stdout);
C = -1;
}
inline void flush() {
if (C > 1 << 22) ot();
}
};
using namespace fast_io;
int n, m, k, Q, T, _, ans = 0;
int in[200007];
vector<int>G[200007],E[200007];
int ord[200007],cnt=0;
int dp[200007];
inline bool topo(){
queue<int>q;
for(int i=1;i<=n;i++) {
if(in[i]==0) q.push(i);
}
while(!q.empty()){
int u=q.front(); q.pop();
ord[++cnt]=u;
for(auto v:G[u]){
in[v]--;
if(in[v]==0) q.push(v);
}
}
if(cnt<n) return 0;
return 1;
}
signed main() {
T=read();
while(T--){
n=read();
for(int i=1;i<=n;i++) {
G[i].clear(),E[i].clear();
in[i]=0;
dp[i]=0;
}
for(int i=1;i<=n;i++){
int l=read();
while(l--){
int x=read();
G[x].push_back(i);
E[i].push_back(x);
in[i]++;
}
}
cnt=0;
bool flag=topo();
if(!flag) {
printf("-1\n");
continue;
}
ans=0;
for(int i=1;i<=cnt;i++){
int u=ord[i];
if(dp[u]==0) dp[u]=1;
for(auto v:G[u]){
if(v>u) dp[v]=max(dp[v],dp[u]);
else dp[v]=max(dp[v],dp[u]+1);
}
ans=max(ans,dp[u]);
}
printf("%d\n",ans);
}
return 0;
}