CF1572A 题解
思路
这题其实就是每次贪心从头读到尾,暂时不能读的就要等下一轮读,直到读完。如果有环就永远读不完。
然后就是拓扑排序板子。但是这题因为每次阅读必须递增,因此我们可以用 set 加上 lower_bound 代替 queue。
代码
# include <bits/stdc++.h>
using namespace std;
int t, n, du[200005], x, sum, now;
vector <int> v[200005];
set <int> q;
int main () {
ios::sync_with_stdio (0);
cin.tie (0);
cout.tie (0);
cin >> t;
while (t --) {
cin >> n;
for (int i = 1; i <= n; ++ i)
du[i] = 0, v[i].clear ();
for (int i = 1; i <= n; ++ i) {
cin >> du[i];
if (! du[i]) //没有入度,加入队列
q.insert (i);
else
for (int j = 0; j < du[i]; ++ j)
cin >> x, v[x].push_back (i);
}
sum = 0;
while (! q.empty ()) {
++ sum, now = 0;
while (1) {
auto it = q.upper_bound (now);
if (it == q.end ())
break ;
int x = now = *it;
q.erase (it);
for (int i : v[x])
if (! -- du[i])
q.insert (i);
}
}
for (int i = 1; i <= n; ++ i)
if (du[i]) { //拓扑完毕还有没理解的,肯定无解
sum = -1;
break ;
}
cout << sum << '\n';
}
return 0;
}

浙公网安备 33010602011771号