Cod sursa(job #2227886)

Utilizator inquisitorAnders inquisitor Data 2 august 2018 09:57:48
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;

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

const int nmax = 1e5+5;
const int mmax = 2e5+5;
const int bmax = 1<<19;
char buff[bmax];
int n, m, dady[nmax], rang[nmax], poz=bmax-1;
pair<int,int> v[mmax];

int Find2(int node){
    while(dady[node]!=node)node=dady[node];
    return node;
}

int Find(int node) {
  int root = node, tmp;

  while (root != dady[root]) {
    root = dady[root];
  }
  while (node != dady[node]) {
    tmp = dady[node];
    dady[node] = root;
    node = tmp;
  }
  return root;
}

void Union(int x, int y){
    dady[x] = y;
}

void Kruskal(){
    int rx, ry, conexe, nr=0, i;
    for(i=1; i<=n; i++)
        dady[i]=i;
    for(i=1; i<=m; i++){
        rx=Find(v[i].first);
        ry=Find(v[i].second);
        if(rx!=ry){
            nr++;
            Union(rx, ry);
        }
    }
    conexe=n-nr;
    fout << conexe;
}

int main(){
    ios_base::sync_with_stdio(false);
    int i;
    fin >> n >> m;
    for(i=1; i<=m; i++)
        fin >> v[i].first >> v[i].second;
    Kruskal();
    fout.close();
    return 0;
}