#include <iostream>
#include <vector>
#include <stack>
using namespace std;
const int maxn=500005;
const int maxm=1000005;
vector<int>nast[maxn];
stack<int>S;
int pop[maxn];
int odw[maxn];
int cykl[maxn];
int aktpop=0;
int aktcykl=1;
int n,m;
void f_cykl(int skrzy){
//cout << "cykl" << aktcykl << " skrzy" << skrzy << endl;
int akt=0;
while(pop[akt]!=skrzy) akt++;
for(int i=akt; i<=aktpop; i++){
// cout << pop[i] << " " << cykl[pop[i]] << endl;
if(cykl[pop[i]]==aktcykl-1) cykl[pop[i]]=aktcykl;
}
aktcykl++;
}
void dfs(int akt){
//cout << "akt " << akt << endl;
odw[akt]=1;
pop[aktpop]=akt;
aktpop++;
for(int i=0;i<nast[akt].size();i++)
if(odw[nast[akt][i]]==0) dfs(nast[akt][i]);
else f_cykl(nast[akt][i]);
aktpop--;
return;
}
int main(){
cin >> n >> m;
for(int i=0; i<m; i++){
int a,b;
cin >> a >> b;
nast[a].push_back(b);
}
for(int i=1; i<=n; i++) if(odw[i]==0) dfs(i);
if(aktcykl==1) cout << "NIE" << endl;
else{
int suma=0;
for(int i=1; i<=n; i++) if(cykl[i]==aktcykl-1) suma++;
if(suma==0) cout << "NIE" << endl;
else{
cout << suma << endl;
for(int i=1; i<=n; i++) if(cykl[i]==aktcykl-1) cout << i << " ";
cout << endl;
}
}
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 | #include <iostream> #include <vector> #include <stack> using namespace std; const int maxn=500005; const int maxm=1000005; vector<int>nast[maxn]; stack<int>S; int pop[maxn]; int odw[maxn]; int cykl[maxn]; int aktpop=0; int aktcykl=1; int n,m; void f_cykl(int skrzy){ //cout << "cykl" << aktcykl << " skrzy" << skrzy << endl; int akt=0; while(pop[akt]!=skrzy) akt++; for(int i=akt; i<=aktpop; i++){ // cout << pop[i] << " " << cykl[pop[i]] << endl; if(cykl[pop[i]]==aktcykl-1) cykl[pop[i]]=aktcykl; } aktcykl++; } void dfs(int akt){ //cout << "akt " << akt << endl; odw[akt]=1; pop[aktpop]=akt; aktpop++; for(int i=0;i<nast[akt].size();i++) if(odw[nast[akt][i]]==0) dfs(nast[akt][i]); else f_cykl(nast[akt][i]); aktpop--; return; } int main(){ cin >> n >> m; for(int i=0; i<m; i++){ int a,b; cin >> a >> b; nast[a].push_back(b); } for(int i=1; i<=n; i++) if(odw[i]==0) dfs(i); if(aktcykl==1) cout << "NIE" << endl; else{ int suma=0; for(int i=1; i<=n; i++) if(cykl[i]==aktcykl-1) suma++; if(suma==0) cout << "NIE" << endl; else{ cout << suma << endl; for(int i=1; i<=n; i++) if(cykl[i]==aktcykl-1) cout << i << " "; cout << endl; } } return 0; } |
English