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
#include <iostream>
#include <cstring>
#include <vector>
#include <stack>
#include <list>

using namespace std;
const int SIZE = 500000+15;

bool visited[SIZE];
vector<int> graph[SIZE];
int k[SIZE]; // krotnosc

stack<int> S;
bool findCycle(int s, int w) {
    visited[w] = true;

    S.push(w);

    for(int i=graph[w].size()-1; i>=0; --i) {
        if(graph[w][i] == s)
            return true;
        if(visited[graph[w][i]] == false && findCycle(s, graph[w][i]) == true)
            return true;
    }

    S.pop();
    return false;
}

int main() {
    ios_base::sync_with_stdio(false);
    memset(k, 0, sizeof(k));

    int n, m;
    cin >> n >> m;

    int a, b;
    for(int i=0; i<m; ++i) {
        cin >> a >> b;
        graph[a].push_back(b);
    }

    int out = 0;

    for(int i=1; i<=n; ++i) {
        memset(visited, false, sizeof(visited));
        S = stack<int>();
        findCycle(i, i);
        //cout << i << ": ";
        if(!S.empty())
        	out++;
        while(!S.empty()) {
        	//cout << S.top() << " ";
            k[S.top()]++;
            S.pop();
        }
        //cout << endl;
    }

    if(out == 0) {
    	cout << "NIE" << endl;
    	return 0;
    }


    list<int> z;
    for(int i=1; i<=n; ++i) {
        if(k[i] == out) {
            z.push_back(i);
        }
    }

    if(z.size() > 0) {
        cout << z.size() << endl;
        for(list<int>::iterator it=z.begin(); it!=z.end(); ++it) {
            cout << *it << " ";
        }
        cout << endl;
    } else {
        cout << "NIE" << endl;
    }

    return 0;
}