Cod sursa(job #2237960)

Utilizator radu.leonardoThe Doctor radu.leonardo Data 4 septembrie 2018 01:19:25
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;
int num_sets;
int num_queries;
int num_connected_components;
vector<int> dad(100001);
vector<int> set_rank(100001);

int find_root(int node) {
    if(node!=dad[node])
        dad[node]=find_root(dad[node]);
    return dad[node];
}

void unite(int first_node,int second_node) {
    int first_root=find_root(first_node);
    int second_root=find_root(second_node);

    if(first_root==second_root)
        return;

    if(set_rank[first_root]<set_rank[second_root])
        swap(first_root,second_root);

    dad[second_root]=first_root;
    if(set_rank[first_root]==set_rank[second_root])
        set_rank[first_root]++;
}

int main() {
    ifstream fin("dfs.in");
    ofstream fout("dfs.out");

    fin>>num_sets>>num_queries;
    num_connected_components=num_sets;

    for(int i=1; i<=num_sets; i++)
        dad[i]=i,set_rank[i]=1;

    for(int i=1; i<=num_queries; i++) {
        int first_node,second_node;
        fin>>first_node>>second_node;
        if(find_root(first_node)!=find_root(second_node)) {
            unite(first_node,second_node);
            num_connected_components--;
        }
    }

    fout<<num_connected_components;

    return 0;
}