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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import java.io.*;
import java.util.*;

class kon {

    public static void main(String[] args) {

        FastScanner in = new FastScanner();
        FastWriter out = null;
        try {
            out = new FastWriter();
        } catch (FileNotFoundException e) {

        }
        int n = in.nextInt();
        int m =in.nextInt();
        int a,b;

        ArrayList<ArrayList<Integer>> adj = new ArrayList<>(n);
        for(int i = 0; i < n; ++i)
        {
            adj.add(new ArrayList<>());
        }

        for(int i = 0; i < m; ++i)
        {
            a = in.nextInt();
            b = in.nextInt();
            --a;
            --b;

            adj.get(a).add(b);
        }

        ElementaryCyclesSearch search = new ElementaryCyclesSearch(adj);
        /*Thread t = new Thread(null, null, "TT", 268435456) {
            @Override
            public void run() {
                search.getElementaryCycles();
            }

        };
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {

        }*/

        search.getElementaryCycles();
        HashMap<Integer, ElementaryCyclesSearch.MutableInt> map = search.map;

        if(search.totalCycles == 0)
        {
           out.println("NIE");
        }
        else {
            List<Integer> l = new ArrayList<>();

            for (Map.Entry<Integer, ElementaryCyclesSearch.MutableInt> entry : map.entrySet()) {
                if (entry.getValue().value == search.totalCycles)
                    l.add(entry.getKey());
            }


            Collections.sort(l);
            out.printNextln(l.size());
            for (int x : l) {
                out.printNext(x + 1);
            }

            out.println();
        }
        out.close();
    }
}

class FastWriter extends PrintWriter {
    FastWriter() throws FileNotFoundException {
        super(System.out);
    }

    void printNext(int i) {
        print(i);
        print(' ');
    }
    void printNextln(int i) {
        print(i);
        println();
    }

    void printNextln(String str) {
        print(str);
        println();
    }

}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;


    boolean ready() throws IOException {
        return (br.ready() || st.hasMoreTokens());
    }

    FastScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

}

class ElementaryCyclesSearch {
    private int[][] adjList = null;
    private boolean[] blocked = null;
    private LinkedList<Integer>[] B = null;
    private Set<Integer>[] BSet = null;
    private Stack<Integer> stack = null;
    public HashMap<Integer, MutableInt> map = new HashMap<>();
    public int totalCycles = 0;

    public ElementaryCyclesSearch(ArrayList<ArrayList<Integer>> adjList)
    {
        this.adjList = new int[adjList.size()][];

        for(int i = 0; i < adjList.size(); i++)
        {
            ArrayList<Integer> l = adjList.get(i);
            this.adjList[i] = new int[adjList.get(i).size()];
            for(int j = 0; j < this.adjList[i].length; j++)
                this.adjList[i][j] = l.get(j);
        }
    }


    public HashMap<Integer, MutableInt> getElementaryCycles() {
        this.blocked = new boolean[this.adjList.length];
        this.BSet = new Set[this.adjList.length];
        this.B = new LinkedList[this.adjList.length];
        for(int i = 0; i < this.adjList.length; i++)
        {
            this.B[i] = new LinkedList<>();
            this.BSet[i] = new HashSet<>();
        }
        this.stack = new Stack<>();
        StrongConnectedComponents sccs = new StrongConnectedComponents(this.adjList);
        int s = 0;

        while (true) {
            SCCResult sccResult = sccs.getAdjacencyList(s);
            if (sccResult != null && sccResult.getAdjList() != null) {
                Vector[] scc = sccResult.getAdjList();
                s = sccResult.getLowestNodeId();
                for (int j = 0; j < scc.length; j++) {
                    if ((scc[j] != null) && (scc[j].size() > 0)) {
                        this.blocked[j] = false;
                        this.B[j].clear();
                        this.BSet[j].clear();
                    }
                }

                this.findCycles(s, s, scc);
                s++;
            } else {
                break;
            }
        }

        return map;
    }
    class MutableInt {
        int value = 1;
        public void increment () { ++value;      }
        public int  get ()       { return value; }
    }


    private boolean findCycles(int v, int s, Vector[] adjList) {
        boolean f = false;
        this.stack.push(v);
        this.blocked[v] = true;

        for (int i = 0; i < adjList[v].size(); i++) {
            int w = ((Integer) adjList[v].get(i)).intValue();
            if (w == s) {
                int x = 0;
                Stack<Integer> dummy = new Stack<>();
                while(!this.stack.empty())
                {
                    int index = stack.pop();
                    x++;
                    MutableInt count = map.get(index);
                    if(count == null)
                        map.put(index, new MutableInt());
                    else
                        count.increment();

                    dummy.push(index);
                }

                while(!dummy.isEmpty())
                {
                    stack.push(dummy.pop());
                }

                if(x > 0)
                    totalCycles++;

                f = true;
            } else if (!this.blocked[w]) {
                if (this.findCycles(w, s, adjList)) {
                    f = true;
                }
            }
        }

        if (f) {
            this.unblock(v);
        } else {
            for (int i = 0; i < adjList[v].size(); i++) {
                int w = ((Integer) adjList[v].get(i)).intValue();
                if (!this.BSet[w].contains(v)) {
                    this.B[w].add(v);
                    this.BSet[w].add(v);
                }
            }
        }

        this.stack.pop();
        return f;
    }

    private void unblock(int node) {
        this.blocked[node] = false;
        LinkedList Bnode = this.B[node];
        while (Bnode.size() > 0) {
            Integer w = (Integer) Bnode.getFirst();
            Bnode.removeFirst();
            BSet[node].remove(w);
            if (this.blocked[w.intValue()]) {
                this.unblock(w.intValue());
            }
        }
    }
}

class SCCResult {
    private HashSet<Integer> nodeIDsOfSCC = null;
    private Vector[] adjList = null;
    private int lowestNodeId = -1;

    public SCCResult(Vector[] adjList, int lowestNodeId) {
        this.adjList = adjList;
        this.lowestNodeId = lowestNodeId;
        this.nodeIDsOfSCC = new HashSet();
        if (this.adjList != null) {
            for (int i = this.lowestNodeId; i < this.adjList.length; i++) {
                if (this.adjList[i].size() > 0) {
                    this.nodeIDsOfSCC.add(new Integer(i));
                }
            }
        }
    }

    public Vector[] getAdjList() {
        return adjList;
    }

    public int getLowestNodeId() {
        return lowestNodeId;
    }
}

class StrongConnectedComponents {
    private int[][] adjListOriginal = null;
    private int[][] adjList = null;
    private boolean[] visited = null;
    private Stack<Integer> stack = null;
    private HashSet<Integer> onStack = new HashSet<>();
    private int[] lowlink = null;
    private int[] number = null;
    private int sccCounter = 0;
    private Vector currentSCCs = null;

    public StrongConnectedComponents(int[][] adjList) {
        this.adjListOriginal = adjList;
    }

    public SCCResult getAdjacencyList(int node) {
        this.visited = new boolean[this.adjListOriginal.length];
        this.lowlink = new int[this.adjListOriginal.length];
        this.number = new int[this.adjListOriginal.length];
        this.visited = new boolean[this.adjListOriginal.length];
        this.stack = new Stack<>();
        this.currentSCCs = new Vector();

        this.makeAdjListSubgraph(node);

        for (int i = node; i < this.adjListOriginal.length; i++) {
            if (!this.visited[i]) {
                this.getStrongConnectedComponents(i);
                HashSet<Integer> nodes = this.getLowestIdComponent();
                if (nodes != null && !nodes.contains(new Integer(node)) && !nodes.contains(new Integer(node + 1))) {
                    return this.getAdjacencyList(node + 1);
                } else {
                    Vector[] adjacencyList = this.getAdjList(nodes);
                    if (adjacencyList != null) {
                        for (int j = 0; j < this.adjListOriginal.length; j++) {
                            if (adjacencyList[j].size() > 0) {
                                return new SCCResult(adjacencyList, j);
                            }
                        }
                    }
                }
            }
        }

        return null;
    }

    private void makeAdjListSubgraph(int node) {
        this.adjList = new int[this.adjListOriginal.length][0];

        for (int i = node; i < this.adjList.length; i++) {
            Vector successors = new Vector();
            for (int j = 0; j < this.adjListOriginal[i].length; j++) {
                if (this.adjListOriginal[i][j] >= node) {
                    successors.add(new Integer(this.adjListOriginal[i][j]));
                }
            }
            if (successors.size() > 0) {
                this.adjList[i] = new int[successors.size()];
                for (int j = 0; j < successors.size(); j++) {
                    Integer succ = (Integer) successors.get(j);
                    this.adjList[i][j] = succ.intValue();
                }
            }
        }
    }

    private HashSet<Integer> getLowestIdComponent() {
        int min = this.adjList.length;
        HashSet<Integer> currScc = null;

        for (int i = 0; i < this.currentSCCs.size(); i++) {
            HashSet<Integer> scc = (HashSet<Integer>) this.currentSCCs.get(i);
            for(Integer node : scc)
            {
                if (node < min) {
                    currScc = scc;
                    min = node;
                }
            }
        }
        return currScc;
    }
    private Vector[] getAdjList(HashSet<Integer> nodes) {
        Vector[] lowestIdAdjacencyList = null;

        if (nodes != null) {
            lowestIdAdjacencyList = new Vector[this.adjList.length];
            for (int i = 0; i < lowestIdAdjacencyList.length; i++) {
                lowestIdAdjacencyList[i] = new Vector();
            }
            for(Integer node : nodes)
            {
                for (int j = 0; j < this.adjList[node].length; j++) {
                    int succ = this.adjList[node][j];
                    if (nodes.contains(new Integer(succ))) {
                        lowestIdAdjacencyList[node].add(new Integer(succ));
                    }
                }
            }
        }

        return lowestIdAdjacencyList;
    }

    private void getStrongConnectedComponents(int root) {
        this.sccCounter++;
        this.lowlink[root] = this.sccCounter;
        this.number[root] = this.sccCounter;
        this.visited[root] = true;
        this.stack.push(new Integer(root));
        this.onStack.add(root);

        for (int i = 0; i < this.adjList[root].length; i++) {
            int w = this.adjList[root][i];
            if (!this.visited[w]) {
                this.getStrongConnectedComponents(w);
                this.lowlink[root] = Math.min(lowlink[root], lowlink[w]);
            } else if (this.number[w] < this.number[root]) {
                if (onStack.contains(w)) {
                    lowlink[root] = Math.min(this.lowlink[root], this.number[w]);
                }
            }
        }

        if ((lowlink[root] == number[root]) && (stack.size() > 0)) {
            int next = -1;
            HashSet<Integer> scc = new HashSet<>();

            do {
                next  =this.stack.pop();
                onStack.remove(next);
                scc.add(next);
            } while (this.number[next] > this.number[root]);

            if (scc.size() > 1) {
                this.currentSCCs.add(scc);
            }
        }
    }
}