咋眼一看,不是拓扑排序裸题吗,写了一堆bug,最后没能A掉,太坑爹了,最后Debug发现是u,v写反了,我真菜,QAQ ,只是比裸题多了一点东西。
这是拓扑排序。
通过思考,你会发现,要是有环,Takahashi就会永远的走下去
首先假设全部都可以走到环上,ans = n;
而只要你遍历到了一个点,就把ans --;
遍历完后,输出答案。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define MAXN 1048586
#define M 1005
#define N 500005
#define debug(...) cout << '[' << 'D' << 'E' << ']' << __LINE__ << ':' << __VA_ARGS__ << endl;
#define vl(x) #x << '(' << x << ')'
#define mod 998244353
#define who(s,limit,tpe) s + tpe , s + limit + tpe
#define all(s) s.begin(),s.end()
#define s_(s) s.size()
int a[N];
int n, m;
string s;
vector<int> G[N];
queue<int> q;
int inde[N];
int top()
{
int ans = n;
for (int i = 1; i <= n; i++)
if (inde[i] == 0) q.push(i);
while (!q.empty())
{
ans --;
int t = q.front();
q.pop();
for (int i = 0; i < s_(G[t]); i++)
{
int y = G[t][i];
inde[y]--;
if (inde[y] == 0)
q.push(y);
}
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
memset(inde, 0, sizeof(inde));
for (int i = 1; i <= n; i++)
G[i].clear();
for (int i = 1; i <= m; i++)
{
int u, v;
cin >> u >> v;
G[v].push_back(u);
inde[u]++;
}
int x = top();
cout << x << endl ;
return 0;
}