#include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; long long current_cykle; long long total_cykle; long long cykle_przez[500001]; long long minusy[500001]; long long cykle_enter[500001]; vector<int> edges[500001]; vector<int> answers; bool visited[500001]; bool onStack[500001]; void DFS(int x){ onStack[x] = true; cykle_enter[x] = current_cykle; for(int i = 0; i < (int)edges[x].size(); ++i){ int ng = edges[x][i]; if(!visited[ng]){ visited[ng] = true; DFS(ng); }else if(onStack[ng]){ // CYKIEL current_cykle++; total_cykle++; minusy[ng]++; } } cykle_przez[x] = current_cykle - cykle_enter[x]; current_cykle -= minusy[x]; onStack[x] = false; } int main(){ int n, m; scanf("%d %d", &n, &m); for(int i = 0; i < m; ++i){ int a, b; scanf("%d %d", &a, &b); edges[a].push_back(b); } total_cykle = 0; current_cykle = 0; for(int i = 1; i <= n; ++i){ minusy[i] = 0; visited[i] = false; onStack[i] = false; } for(int i = 1; i <= n; ++i){ if(!visited[i]){ visited[i] = true; DFS(i); } } if(total_cykle == 0){ printf("NIE\n"); return 0; } for(int i = 1; i <= n; ++i){ if(cykle_przez[i] == total_cykle){ answers.push_back(i); } } sort(answers.begin(), answers.end()); printf("%d\n", (int)answers.size()); for(int i = 0; i < (int)answers.size(); ++i){ printf("%d ", answers[i]); } printf("\n"); 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 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 | #include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; long long current_cykle; long long total_cykle; long long cykle_przez[500001]; long long minusy[500001]; long long cykle_enter[500001]; vector<int> edges[500001]; vector<int> answers; bool visited[500001]; bool onStack[500001]; void DFS(int x){ onStack[x] = true; cykle_enter[x] = current_cykle; for(int i = 0; i < (int)edges[x].size(); ++i){ int ng = edges[x][i]; if(!visited[ng]){ visited[ng] = true; DFS(ng); }else if(onStack[ng]){ // CYKIEL current_cykle++; total_cykle++; minusy[ng]++; } } cykle_przez[x] = current_cykle - cykle_enter[x]; current_cykle -= minusy[x]; onStack[x] = false; } int main(){ int n, m; scanf("%d %d", &n, &m); for(int i = 0; i < m; ++i){ int a, b; scanf("%d %d", &a, &b); edges[a].push_back(b); } total_cykle = 0; current_cykle = 0; for(int i = 1; i <= n; ++i){ minusy[i] = 0; visited[i] = false; onStack[i] = false; } for(int i = 1; i <= n; ++i){ if(!visited[i]){ visited[i] = true; DFS(i); } } if(total_cykle == 0){ printf("NIE\n"); return 0; } for(int i = 1; i <= n; ++i){ if(cykle_przez[i] == total_cykle){ answers.push_back(i); } } sort(answers.begin(), answers.end()); printf("%d\n", (int)answers.size()); for(int i = 0; i < (int)answers.size(); ++i){ printf("%d ", answers[i]); } printf("\n"); return 0; } |