Cod sursa(job #3168920)

Utilizator Barbu_MateiBarbu Matei Barbu_Matei Data 13 noiembrie 2023 19:13:15
Problema Paduri de multimi disjuncte Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
using namespace std;

unordered_map<int, unordered_map<int, bool>> mt;
int n, m, nodMax;

bool bfs(int start, int searched) {
    bool viz[100001] = {0};
    queue<int> q;
    q.push(start);
    viz[start] = 1;
    while (!q.empty()) {
        int nod = q.front();
        q.pop();
        if (nod == searched) {
            return true;
        }
        for (int j = 0; j <= nodMax; ++j) {
            if (mt[nod][j] != 0 && viz[j] == 0) {
                q.push(j);
                viz[j] = 1;
            }
        }
    }
    return false;
}

int main() {
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");
    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int c, x, y;
        cin >> c >> x >> y;
        nodMax = max(max(nodMax, x), y);
        if (c == 1) {
            mt[x][y] = 1;
            mt[y][x] = 1;
        } else {
            if(bfs(x, y)) {
                cout << "DA";
            } else {
                cout << "NU";
            }
            cout << "\n";
        }
    }
}