Cod sursa(job #2594601)

Utilizator RazorBestPricop Razvan Marius RazorBest Data 6 aprilie 2020 13:38:51
Problema Parcurgere DFS - componente conexe Scor 20
Compilator c-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <stdio.h>
#include <string.h>
#define NMAX 100000

typedef struct {
    int a;
} LinkedList;

void init(int *t, int n) {
    for (int i = 0; i < n; i++) {
        t[i] = 0;
    }
}

int get_root(int *t, int node) {
    int root = node, next;

    while (t[root] != 0) {
        root = t[root];
    }

    while (t[node] != 0) {
        next = t[node];
        t[node] = root;
        node = next;
    }

    return root;
}

void merge(int *t, int root1, int root2) {
    t[root1] = root2;
}

int main() {
    int n, m, x, y, t[NMAX + 1], cnt = 0;
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);

    scanf("%d%d", &n, &m);
    memset(t, 0, (n + 1) * sizeof(int));
    
    while (m--) {
        scanf("%d%d", &x, &y);
        int root1 = get_root(t, x), root2 = get_root(t, y);
        merge(t, root1, root2);
    }

    for (int i = 1; i <= n; i++) {
        if (t[i] == 0) {
            cnt++;
        }
    }

    printf("%d", cnt);
}