Cod sursa(job #2943948)

Utilizator TeoDiDiaconescu Teodora TeoDi Data 21 noiembrie 2022 20:58:53
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m;

void Cer1(vector<pair<int,int> >& v, int x, int y){
    int xc = x, yc = y, ok = 0;
    while(v[x].first != -1) x = v[x].first;
    while(v[y].first != -1)
        y = v[y].first;
    if(v[x].second < v[y].second) swap(x, y), swap(xc, yc);
    v[y].first = x;
    v[x].second += v[y].second;
    while(v[yc].first != x) {
        xc = v[yc].first;
        v[yc].first = x;
        yc = xc;
    }
}

bool Cer2(vector<pair<int,int> >& v, int x, int y){
    int xc = x, yc = y, aux;
    if(x == y) return true;
    while(v[x].first != -1 && x != y) x = v[x].first;
    if(x == y){
        while(v[y].first != -1) y = v[y].first;
        while(v[xc].first != y) {
            aux = v[xc].first;
            v[xc].first = y;
            xc = aux;
        }
        return true;
    }
    while(v[y].first != -1) y = v[y].first;
    if(x == y)
    {
        while(v[xc].first != -1) {
            aux = v[xc].first;
            v[xc].first = x;
            xc = aux;
        }
        while(v[yc].first != -1) {
            aux = v[yc].first;
            v[yc].first = y;
            yc = aux;
        }
        return true;
    }
    else{
        while(v[xc].first != -1) {
            aux = v[xc].first;
            v[xc].first = x;
            xc = aux;
        }
        while(v[yc].first != -1) {
            aux = v[yc].first;
            v[yc].first = y;
            yc = aux;
        }
        return false;
    }
}

void Citire()
{
    fin>>n>>m;
    vector<pair<int,int> > v(n+1, make_pair(-1, 1));
    int c, x, y;
    for(int i = 0; i < m; i++){
        fin>>c>>x>>y;
        if(c == 1){
            Cer1(v, x, y);
        }
        else if(c == 2){
            bool ok = Cer2(v, x, y);
            if(!ok) fout<<"NU\n";
            else fout<<"DA\n";
        }
        else{
            fout<<"Input invalid\n";
        }
        //for(int i = 1; i <= n; i++) cout<<v[i].first<<' '<<v[i].second<<' ';
        //cout<<'\n';
    }
}

int main() {
    Citire();
    return 0;
}