#include<bits/stdc++.h>
using namespace std;
vector<int> v[500009];
int tc[500009],cykli;
int tg[500009];
bool tb[500009],tw[500009];
priority_queue<int> kol;
void dfs(int x)
{
vector<int> pom;
tb[x]=true;
for(vector<int>::iterator it=v[x].begin();it!=v[x].end();++it)
if(!tb[*it])
{
tg[*it]=tg[x]+1;
dfs(*it);
}
else if(!tw[*it]) pom.push_back(*it);
for(vector<int>::iterator it=pom.begin();it!=pom.end();++it)
{
kol.push(tg[*it]);
++cykli;
}
while(!kol.empty() && kol.top()>tg[x]) kol.pop();
tc[x]=kol.size();
tw[x]=true;
}
int main()
{
int n,m,a,b;
vector<int> wyn;
scanf("%d%d",&n,&m);
for(int i=0;i<m;++i)
{
scanf("%d%d",&a,&b);
v[a].push_back(b);
}
for(int i=1;i<=n;++i)
if(!tb[i]) dfs(i);
if(cykli==0)
{
printf("NIE");
return 0;
}
for(int i=1;i<=n;++i) if(tc[i]==cykli) wyn.push_back(i);
sort(wyn.begin(),wyn.end());
printf("%d\n",wyn.size());
for(vector<int>::iterator it=wyn.begin();it!=wyn.end();++it) printf("%d ",*it);
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 | #include<bits/stdc++.h> using namespace std; vector<int> v[500009]; int tc[500009],cykli; int tg[500009]; bool tb[500009],tw[500009]; priority_queue<int> kol; void dfs(int x) { vector<int> pom; tb[x]=true; for(vector<int>::iterator it=v[x].begin();it!=v[x].end();++it) if(!tb[*it]) { tg[*it]=tg[x]+1; dfs(*it); } else if(!tw[*it]) pom.push_back(*it); for(vector<int>::iterator it=pom.begin();it!=pom.end();++it) { kol.push(tg[*it]); ++cykli; } while(!kol.empty() && kol.top()>tg[x]) kol.pop(); tc[x]=kol.size(); tw[x]=true; } int main() { int n,m,a,b; vector<int> wyn; scanf("%d%d",&n,&m); for(int i=0;i<m;++i) { scanf("%d%d",&a,&b); v[a].push_back(b); } for(int i=1;i<=n;++i) if(!tb[i]) dfs(i); if(cykli==0) { printf("NIE"); return 0; } for(int i=1;i<=n;++i) if(tc[i]==cykli) wyn.push_back(i); sort(wyn.begin(),wyn.end()); printf("%d\n",wyn.size()); for(vector<int>::iterator it=wyn.begin();it!=wyn.end();++it) printf("%d ",*it); return 0; } |
English