1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include <bits/stdc++.h>
#define MAX_N 100001 #define ll long long #define pll pair<ll, ll> #define vpll vector<pll> #define vll vector<ll> #define vvll vector<vll> #define all(a) begin(a), end(a) using namespace std;
ll n, e; bool vis1[MAX_N], vis2[MAX_N], vis3[MAX_N]; ll rep[MAX_N]; vll st;
void dfs1(ll u, vvll& adj) { vis1[u] = true; for(auto& v : adj[u]) if(!vis1[v]) dfs1(v, adj); st.push_back(u); }
void dfs2(ll u, ll r, vvll& radj) { vis2[u] = true; rep[u] = r; for(auto& v : radj[u]) if(!vis2[v]) dfs2(v, r, radj); }
ll solve(vpll& edges) { vvll adj(n + 1), radj(n + 1); memset(vis1, 0, sizeof(vis1)); memset(vis2, 0, sizeof(vis2)); memset(vis3, 0, sizeof(vis3)); memset(rep, 0, sizeof(rep));
for(auto& [u, v] : edges) { adj[u].push_back(v); radj[v].push_back(u); }
for(ll i = 1; i <= n; i++) if(!vis1[i]) dfs1(i, adj);
while(!st.empty()) { auto u = st.back(); st.pop_back(); if(!vis2[u]) dfs2(u,u,radj); }
ll res = 0; unordered_set<ll> usll; for(auto& [u, v] : edges) { if(rep[u] == rep[v]) continue; usll.insert(rep[v]); }
for(ll i = 1; i <= n; i++) { if(vis3[rep[i]]) continue; vis3[rep[i]] = true; if(!usll.count(rep[i])) res++; }
return res; }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); ll tc; cin>>tc; while(tc--) { cin>>n>>e; ll u, v; vpll edges; while(e--) { cin>>u>>v; edges.push_back({u,v}); } cout<<solve(edges)<<'\n'; }
return 0; }
|