Cod sursa(job #2875560)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 21 martie 2022 21:36:15
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>
#define FIND(arr, x) find(arr.begin(), arr.end(), x)

using namespace std;

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

struct Node {
    vector<int> arr;
    Node *prev, *next;

    static Node* findN(Node *head, int n) {
        while (head && FIND(head->arr, n) == head->arr.end())
            head = head->next;
        return head;
    }

    static void merge(Node **head, int x, int y) {
        Node *xhead = Node::findN(*head, x), *yhead = Node::findN(*head, y);
        if (!xhead || !yhead)
            return;

        for (auto &n : yhead->arr) //merge
            xhead->arr.push_back(n);

        //deleting
        if (!yhead->next)
            yhead->prev->next = nullptr;
        else if (!yhead->prev)
            *head = yhead->next, (*head)->prev = nullptr;
        else
            yhead->prev->next = yhead->next, yhead->next->prev = yhead->prev;
        delete yhead;
    }

    static bool check(Node* head, int x, int y) {
        return Node::findN(head, x) == Node::findN(head, y);
    }
};


int main() {
    int n, m;
    fin >> n >> m;
    Node *head = new Node{{1}, nullptr, nullptr}, *curr = head;
    for (int i = 2; i <= n; i++) {
        curr->next = new Node{{i}, curr, nullptr};
        curr = curr->next;
    }

    for (int i = 0; i < m; i++) {
        int t, x, y;
        fin >> t >> x >> y;
        switch (t) {
            case 1:
                Node::merge(&head, x, y);
                break;
            case 2:
                fout << (Node::check(head, x, y) ? "DA" : "NU") << '\n';
                break;
        }
    }

    curr = head;
    while (curr) {
        Node *aux = curr->next;
        delete curr;
        curr = aux;
    }
    return 0;
}