Cod sursa(job #3195231)

Utilizator KRISTY06Mateiu Ianis Cristian Vasile KRISTY06 Data 20 ianuarie 2024 11:50:04
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.39 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAX_SIZE = 100000;

int tree[MAX_SIZE + 1];

int treeHeight(int startNode) {
    int currentNode = startNode, height = 0;
    while (tree[currentNode] != 0) {
        currentNode = tree[currentNode];
        ++height;
    }
    return height;
}

int findRoot(int startNode) {
    int currentNode = startNode;
    while (tree[currentNode] != 0) {
        currentNode = tree[currentNode];
    }
    return currentNode;
}

void uniteTrees(int root, int startNode) {
    int currentNode = startNode;
    while (tree[currentNode] != 0) {
        int aux = tree[currentNode];
        tree[currentNode] = root;
        currentNode = aux;
    }
    if (currentNode != root) {
        tree[currentNode] = root;
    }
}

int main() {
    int noNodes, noOperations;
    fin >> noNodes >> noOperations;
    for (int i = 1; i <= noOperations; ++i) {
        int operation, node1, node2;
        fin >> operation >> node1 >> node2;
        int node1Root = findRoot(node1), node2Root = findRoot(node2);
        if (operation == 1) {
            if (treeHeight(node1) > treeHeight(node2)) {
                uniteTrees(node1Root, node2);
                uniteTrees(node1Root, node1);
               // tree[findRoot(node2)] = findRoot(node1);
            } else {
                uniteTrees(node2Root, node1);
                uniteTrees(node2Root, node2);
               // tree[findRoot(node1)] = findRoot(node2);
            }
        } else {
            if (node1Root == node2Root) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
    }
    return 0;
}
/*

1) Cazul din problema:

4 3
1 4 1
2 4 2
2 4 1
=>
NU
DA

2) Cazul cand toate nodurile formeaza o singura multime:

3 5
1 1 2
1 1 3
2 1 2
2 1 3
2 3 2
=>
DA
DA
DA

3) Cazul cand nu exista nici o operatie de tip 1 si atunci pentru orice operatie de tip 2 raspunsul va fi "NU":

3 3
2 2 1
2 3 1
2 3 2
=>
NU
NU
NU

4) Cazul in care nu exista nici o operatie de tip 2:

2 1
1 1 2
=>
(nimic)

5) Cazul cand inainte de operatiile de tipul 2 avem numai 2 submultimi:

4 6
1 1 2
1 2 3
1 4 5
1 4 6
2 1 4
2 5 6
=>
NU
DA

6) Cazul din problema:

4 6
1 1 2
1 3 4
2 1 3
2 1 2
1 1 3
2 1 4
=>
NU
DA
DA

*/