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

using namespace std;

const int maxn = 5 * 1e5;
vector<int> g[maxn+1];
vector<int> cycle;
stack<int> depth;

int color[maxn+1];
vector<int> result;

bool csearch(int x) {
	color[x] = 1;
	depth.push(x);

	bool r;
	for (int i = 0; i < g[x].size(); i++) {
		int y = g[x][i];
		if (color[y] == 0) {
			r = csearch(y);
			if (r) break;
		} else if (color[y] == 1) {
			cycle.push_back(y);
			while (depth.top() != y) {
				cycle.push_back(depth.top());
				depth.pop();
			}
			r = true;
			break;
		}
	}

	depth.pop();
	color[x] = 2;
	return r;
}

bool csearch_v(int x, int l) {
	color[x] = l;

	for (int i = 0; i < g[x].size(); i++) {
		int y = g[x][i];
		if (color[y] < l) {
			if (csearch_v(y, l)) {
				return true;
			}
		} else if (color[y] == l) {
			return true;
		}
	}

	color[x] = l+1;
	return false;
}

int main() {
	ios_base::sync_with_stdio(0);

	int n, m, a, b;
	cin >> n >> m;

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

	bool c;
	for (int i = 0; i < n; i++) {
		if (color[i+1] == 0) {
			c = csearch(i+1);
			if (c) break;
		}
	}

	if (c) {
		int turn = 3; bool res;
		int all = 0;
		for (int i = 0; i < cycle.size(); i++) {
			color[cycle[i]] = turn + 1;
			if (all == 0) {
				for (int j = 0; j < n; j++) {
					if (color[j+1] < turn) {
						res = csearch_v(j+1, turn);
						if (res) break;
					}
				}
				if (!res) all = cycle[i];
			} else {
				res = csearch_v(all, turn);
			}

			if (!res) result.push_back(cycle[i]);
			turn += 2;
		}

		sort(result.begin(), result.end());

		cout << result.size() << endl;
		for (int i = 0; i < result.size(); i++) {
			cout << result[i] << ' ';
		}
		cout << endl;
	} else {
		cout << "NIE" << endl;
	}

	return 0;
}