#include <cstdio> #include <vector> using namespace std; struct Node{ vector<int> outedges; int t; bool available=true; }; int n,m; Node g[500009]; int topo; void Dfs(int v){ if(!g[v].t && g[v].available){ g[v].t=1; for(int e : g[v].outedges) Dfs(e); g[v].t = --topo; } } void TopoSort(){ for(int i=1;i<=n;++i) g[i].t=0; topo = n; for(int i=1;i<=n;++i) Dfs(i); } bool isAcyclic(){ TopoSort(); for(int i=1;i<=n;++i){ if(!g[i].available) continue; for(int e : g[i].outedges){ if(g[e].available && g[i].t >= g[e].t) return false; } } return true; } int main(){ scanf("%d%d",&n,&m); for(int i=0;i<m;++i){ int a,b; scanf("%d%d",&a,&b); g[a].outedges.push_back(b); } if(isAcyclic()){ puts("NIE"); }else{ vector<int> pewne; for(int i=1;i<=n;++i){ g[i].available = false; if(isAcyclic()) pewne.push_back(i); g[i].available = true; } printf("%d\n",pewne.size()); for(int i=0;i<pewne.size();++i){ printf("%d ",pewne[i]); } puts(""); } return 0; }
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 | #include <cstdio> #include <vector> using namespace std; struct Node{ vector<int> outedges; int t; bool available=true; }; int n,m; Node g[500009]; int topo; void Dfs(int v){ if(!g[v].t && g[v].available){ g[v].t=1; for(int e : g[v].outedges) Dfs(e); g[v].t = --topo; } } void TopoSort(){ for(int i=1;i<=n;++i) g[i].t=0; topo = n; for(int i=1;i<=n;++i) Dfs(i); } bool isAcyclic(){ TopoSort(); for(int i=1;i<=n;++i){ if(!g[i].available) continue; for(int e : g[i].outedges){ if(g[e].available && g[i].t >= g[e].t) return false; } } return true; } int main(){ scanf("%d%d",&n,&m); for(int i=0;i<m;++i){ int a,b; scanf("%d%d",&a,&b); g[a].outedges.push_back(b); } if(isAcyclic()){ puts("NIE"); }else{ vector<int> pewne; for(int i=1;i<=n;++i){ g[i].available = false; if(isAcyclic()) pewne.push_back(i); g[i].available = true; } printf("%d\n",pewne.size()); for(int i=0;i<pewne.size();++i){ printf("%d ",pewne[i]); } puts(""); } return 0; } |