A. Book
原题链接
题解
在一个章节更新过后,更新其周围章节的首次阅读时间,如果周围章节在其后面,时间不变,如果在其前面,时间加一
当一个章节的前置章节都更新完之后再更新其周围章节
code
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int in[200005]={0};
vector<int> edge[200005];
int ti[200005]={0};
void solve()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
edge[i].clear();
in[i]=0;
ti[i]=0;
}
for(int i=1;i<=n;i++)
{
int k;
cin>>k;
in[i]=k;
for(int j=1;j<=k;j++)
{
int x;
cin>>x;
edge[x].push_back(i);
}
}
queue<int> q;
for(int i=1;i<=n;i++)
if(!in[i])
{
q.push(i);
ti[i]=1;
}
while(q.size())
{
int now=q.front();
q.pop();
for(auto next:edge[now])
{
if(next>now) ti[next]=max(ti[next],ti[now]);
else ti[next]=max(ti[next],ti[now]+1);
in[next]--;
if(!in[next]) q.push(next);
}
}
bool judge=1;
int ans=0;
for(int i=1;i<=n;i++)
{
if(in[i]) judge=0;//仍然有边存在
ans=max(ans,ti[i]);
}
if(judge) cout<<ans<<'\n';
else cout<<"-1\n";
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int t=1;
cin>>t;
while(t--) solve();
return 0;
}