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
| #include <bits/stdc++.h>
#define MAX_N 10001 #define ll long long #define pll pair<ll, ll> #define vpll vector<pll> #define vll vector<ll> #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, vector<vll>& 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, vector<vll>& radj) { rep[u] = r; vis2[u] = true; for(auto& v : radj[u]) { if(!vis2[v]) dfs2(v, r, radj); } }
vll solve(vpll& edges) { vector<vll> 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()) { ll u = st.back(); st.pop_back(); if(!vis2[u]) dfs2(u, u, radj); }
unordered_set<ll> usll; for(auto& [u, v] : edges) { if(rep[u] == rep[v]) continue; usll.insert(rep[u]); }
vll res; for(ll i = 1; i<= n; i++) if(!usll.count(rep[i])) res.push_back(i);
return res; }
int main() { ios_base::sync_with_stdio(0); cin.tie(0); while(true) { cin>>n; if(!n) break; cin>>e; ll u, v; vpll edges; while(e--) { cin>>u>>v; edges.push_back({u,v}); } auto res = solve(edges); for(auto& c : res) cout<<c<<' ';cout<<'\n'; } return 0; }
|