Cod sursa(job #1969002)

Utilizator mariakKapros Maria mariak Data 18 aprilie 2017 09:04:36
Problema Strazi Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.58 kb
/*   Find the number of directed paths then add nr_path - 1 edges*/


#include <bits/stdc++.h>
#define maxN 260
FILE *fin  = freopen("strazi.in", "r", stdin);
FILE *fout = freopen("strazi.out", "w", stdout);

using namespace std;
int N, M;
vector <int> G[maxN];
int path[maxN], lead[maxN], no_path;
queue <int> q;
bitset <maxN> boss;
bitset <maxN> used;
vector <int> sol;

void dfs(int node){
    boss.set(node);
    for(int son : G[node]){
        if(path[son] && !boss.test(son)) // internal node
            continue;
        if(!path[son])
            dfs(son);
        if(!path[node]){
            path[node] = path[son];
            boss.reset(son);
            boss.set(node);
        }
    }
    if(!path[node])
        path[node] = ++no_path;
}

void read(){
    scanf("%d %d", &N, &M);
    for(int i = 1; i <= M; ++ i){
        int x, y;
        scanf("%d %d", &x, &y);
        G[x].push_back(y);
    }
}

int new_lst(int node){
    sol.push_back(node);
    for(int son : G[node])
        if(path[son] == path[node])
            return new_lst(son);
    if(G[node].size() == 0)
        return node;
}

int main(){
    read();
    for(int i = 1; i <= N; ++ i)
        if(!path[i])
            dfs(i);
    int lst = 0;
    printf("%d\n", no_path - 1);
    for(int i = 1; i <= N; ++ i)
        if(!used.test(path[i]) && boss.test(i)){
            if(lst)
                printf("%d %d\n", lst, i);
            lst = new_lst(i);
            used.set(path[i]);
        }

    for(int node : sol)
        printf("%d ", node);
    return 0;
}