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
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;

#define MAX_N 500000

int n,m;
vector<int> V[MAX_N];
vector<int> T[MAX_N];

int postOrder[MAX_N];
bool visited[MAX_N];
int C[MAX_N];
int componentsCount=0;

vector<int> Q;

inline void clearVisited(){
    memset(visited,0,n);
}

void calcPostOrder(int i,int& v){
    visited[i]=1;
    for(int x:V[i]){
        if(!visited[x]){
            calcPostOrder(x,v);
        }
    }
    postOrder[v++]=i;
}

int calcC(int i,int c){
    visited[i]=1;
    C[i]=c;
    int ret=1;
    for(int x:T[i]){
        if(!visited[x]){
            ret+=calcC(x,c);
        }
    }
    return ret;
}

int calcC2(int i,int c,int z){
    visited[i]=1;
    int ret=1;
    for(int x:T[i]){
        if(C[x]==0 && !visited[x] && x!=z){
            ret+=calcC2(x,c,z);
        }
    }
    return ret;
}

void calcPostOrder2(int i,int& v,int z){
    visited[i]=1;
    for(int x:V[i]){
        if(C[x]==0 && !visited[x] && x!=z){
            calcPostOrder2(x,v,z);
        }
    }
    postOrder[v++]=i;
}

bool hasCycle(int z){
    int num=0;
    for(int x:Q){
        if(!visited[x] && x!=z){
            calcPostOrder2(x,num,z);
        }
    }
    clearVisited();
    int ret=0;
    for(int a=num-1;a>=0;--a){
        if(!visited[postOrder[a]]){
            if(calcC2(postOrder[a],ret++,z)==1){
                ret--;
            }else return 1;
        }
    }
    return 0;
}

int main(){
    scanf("%d%d",&n,&m);
    for(int a=0;a<m;++a){
        int q,w;
        scanf("%d%d",&q,&w);
        V[--q].push_back(--w);
        T[w].push_back(q);
    }
    for(int a=0,number=0;a<n;++a){
        if(!visited[a]){
            calcPostOrder(a,number);
        }
    }
    clearVisited();
    for(int a=n-1;a>=0;--a){
        if(!visited[postOrder[a]]){
            if(calcC(postOrder[a],componentsCount++)==1){
                C[postOrder[a]]=-1;
                componentsCount--;
            }
        }
    }
    if(componentsCount==0){
        printf("NIE");
        return 0;
    }
    if(componentsCount>1){
        printf("0\n");
        return 0;
    }

    for(int a=0;a<n;++a){
        if(C[a]==0)Q.push_back(a);
    }

    vector<int> ans;
    for(int x:Q){
        clearVisited();
        if(!hasCycle(x))
            ans.push_back(x);
    }

    printf("%d\n",ans.size());
    for(int x:ans){
        printf("%d ",x+1);
    }

    return 0;
}