Cod sursa(job #2668737)

Utilizator Alex_tz307Lorintz Alexandru Alex_tz307 Data 5 noiembrie 2020 11:51:53
Problema Ciclu hamiltonian de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.35 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("componentebiconexe.in");
ofstream fout("componentebiconexe.out");

vector < int > id, low_id, articulations;
vector < vector < int > > G, Components;
stack < pair < int , int > > S;
vector < pair < int , int > > bridges;

inline void min_self(int& a, int b) {
    a = min(a, b);
}

void BC(int u, int v) {
    vector < int > new_c;
    int x, y;
    do {
        x = S.top().first, y = S.top().second;
        S.pop();
        new_c.emplace_back(x), new_c.emplace_back(y);
    } while(x != u || y != v);
    Components.emplace_back(new_c);
}

void DFS(int node, int parent, int val) {
    id[node] = low_id[node] = val;
    int cnt = 0;
    for(int vec : G[node]) {
        if(vec == parent)
            continue;
        ++cnt;
        if(id[vec] == -1) {
            S.emplace(node, vec);
            DFS(vec, node, val + 1);
            min_self(low_id[node], low_id[vec]);
            if(low_id[vec] >= id[node]) {
                if(low_id[vec] > id[node])
                    bridges.emplace_back(node, vec);
                BC(node, vec);
                if(node != 1)
                    articulations.emplace_back(node);
            }
        }
        else
            min_self(low_id[node], id[vec]);
    }
}

int main() {
    fin.sync_with_stdio(false);
    fout.sync_with_stdio(false);
    fin.tie(nullptr);
    fout.tie(nullptr);
    int task, N, M;
    fin >> task >> N >> M;
    G.resize(N + 1), id.assign(N + 1, -1), low_id.resize(N + 1);
    while(M--) {
        int u, v;
        fin >> u >> v;
        G[u].emplace_back(v);
        G[v].emplace_back(u);
    }
    DFS(1, 0, 0);
    if(task == 1) {
        fout << Components.size() << '\n';
        for(auto C : Components) {
            sort(C.begin(), C.end());
            C.erase(unique(C.begin(), C.end()), C.end());
            fout << C.size() << ' ';
            for(int node : C)
                fout << node << ' ';
            fout << '\n';
        }
    }
    else
        if(task == 2) {
            fout << articulations.size() << '\n';
            for(int node : articulations)
                fout << node << ' ';
        }
    else {
        fout << bridges.size() << '\n';
        for(auto b : bridges)
            fout << b.first << ' ' << b.second << '\n';
    }
}