Cod sursa(job #2919826)

Utilizator flibiaVisanu Cristian flibia Data 19 august 2022 22:55:16
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>

using namespace std;
 
#ifdef LOCAL
#include "debug.h"
#else
#define dbg(...) 69
#define nl(...) 42
#endif

#define ll long long
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll random(ll st, ll dr) {
    assert(st <= dr);
    return st + rng() % (dr - st + 1);
}

struct Node {
    int val;
    Node *next;
    Node(int val) : val(val), next(nullptr) {}
};

Node* add(Node *node, int val) {
    if (!node) {
        node = new Node(val);
        return node;
    }
    Node *nw = new Node(val);
    nw->next = node;
    return nw;
}

const int MOD = 1e9 + 7;
const int N = 1e5 + 10;

int n, m, x, y;
Node* v[N];
int viz[N];

void dfs(int x) {
    viz[x] = 1;
    while (v[x]) {
        if (!viz[v[x]->val]) {
            dfs(v[x]->val);
        }
        v[x] = v[x]->next;
    }
}

void solve(int test, istream &cin, ostream &cout) {
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        cin >> x >> y;
        v[x] = add(v[x], y);
        v[y] = add(v[y], x);
    }

    int nr = 0;
    for (int i = 1; i <= n; i++) {
        if (!viz[i]) {
            dfs(i);
            nr++;
        }
    }

    cout << nr;
}

int main() {
    ifstream cin("dfs.in");
    ofstream cout("dfs.out");
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    auto start = std::chrono::high_resolution_clock::now();

    bool multiTest = false;

    int t;    
    if (multiTest) {
        cin >> t;
    } else {
        t = 1;
    }

    for (int test = 1; test <= t; test++) {
        solve(test, cin, cout);
    }

    auto stop = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    // cerr << fixed << setprecision(6) << "Running time: " << (double) duration.count() / 1e6 << " seconds" << '\n';

    return 0;
}