Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # include <iostream>
- # include <vector>
- # include <algorithm>
- # define ll long long
- using namespace std;
- ll index, kol_compo;
- ll color[100100], low_link[100100], id[100100], in_srr[100100], pred[100100];
- vector< ll > srr, tops;
- vector< ll > Gr[100100], new_Gr[100100], from[100100], compo[100100];
- void way(ll v)
- {
- color[v] = 1;
- for(ll x : Gr[v]){
- if(color[x] == 0) way(x);
- }
- for(ll x : from[v]){
- if(color[x] == 0) way(x);
- }
- }
- void Tarjan(ll v)
- {
- color[v] = 1;
- low_link[v] = index;
- id[v] = index;
- index++;
- srr.push_back(v);
- in_srr[v] = 1;
- for(ll x : Gr[v]){
- if(color[x] == 0){
- Tarjan(x);
- low_link[v] = min(low_link[v], low_link[x]);
- }
- else if(in_srr[x] == 1){
- low_link[v] = min(low_link[v], id[x]);
- }
- }
- if(id[v] == low_link[v]){
- kol_compo++;
- int x;
- do {
- x = srr.back();
- srr.pop_back();
- in_srr[x] = 0;
- compo[kol_compo].push_back(x);
- pred[x] = kol_compo;
- } while(x != v);
- }
- }
- void top_sort(ll v)
- {
- color[v] = 1;
- for(ll x : new_Gr[v]){
- if(color[x] == 0) top_sort(x);
- }
- tops.push_back(v);
- }
- int main()
- {
- ios_base::sync_with_stdio(0);
- cin.tie(NULL);
- cout.tie(NULL);
- ll n, m, a, b, i;
- cin >> n >> m;
- for(i = 1; i <= m; i++){
- cin >> a >> b;
- Gr[a].push_back(b);
- from[b].push_back(a);
- }
- /// Step 1 : Chek all nodes - in one component unorder Graph
- fill(color + 1, color + 1 + n, 0);
- way(1);
- for(i = 1; i <= n; i++){
- if(color[i] == 0){
- cout << "0";
- return 0;
- }
- }
- /// Step 2 : Find all strong components
- /// Step 3 : Fill pred[ ] where pred[x] = y, mean x - in strong component number y
- index = 0;
- fill(color + 1, color + 1 + n, 0);
- for(i = 1; i <= n; i++){
- if(color[i] == 0) Tarjan(i);
- }
- /// Step 4 : Make new Graph
- for(i = 1; i <= kol_compo; i++){
- for(ll v : compo[i]){
- for(ll x : Gr[v]){
- if(pred[x] != i) new_Gr[i].push_back(pred[x]);
- }
- }
- }
- /// Step 5 : Make nodes in new_Graph topological sort
- fill(color + 1, color + 1 + n, 0);
- for(i = 1; i <= n; i++){
- if(color[i] == 0) top_sort(i);
- }
- ///reverse(tops.begin(), tops.end());
- /// Step 6 : sort Answer is first node in tops
- sort(compo[tops[0]].begin(), compo[tops[0]].end());
- /// Step 7 : Answer is first node in tops
- cout << compo[tops[0]].size() << '\n';
- for(ll v : compo[tops[0]]){
- cout << v << " ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement