Cod sursa(job #1408974)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 30 martie 2015 12:46:43
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 100000 + 10;

int n;

struct node {
  node *p, *ch[2];
  inline bool d() { return this == p->ch[1]; }
  inline bool isroot() { return !p || (this != p->ch[0] && this != p->ch[1]); }
};

node pool[N];

inline void rotate(node *u) {
  node *v = u->p;
  bool d = u->d();
  if (!v->isroot()) v->p->ch[v->d()] = u;
  u->p = v->p;
  if (u->ch[!d]) u->ch[!d]->p = v;
  v->ch[d] = u->ch[!d];
  u->ch[!d] = v;
  v->p = u;
}

inline void splay(node *u) {
  while (!u->isroot()) {
    if (u->p->isroot())
      rotate(u);
    else
      (u->d() == u->p->d()) ? (rotate(u->p), rotate(u)) : (rotate(u), rotate(u));
  }
}

inline node* expose(node *u) {
  node *v;
  for (v = NULL; u; v = u, u = u->p) {
    splay(u);
    u->ch[1] = v;
  }
  return v;
}

inline void link(node *u, node *v) {
  splay(u);
  u->p = v;
}

inline void cut(node *u) {
  expose(u);
  splay(u);
  u->ch[0]->p = NULL;
  u->ch[0] = NULL;
}

inline node* lca(node *u, node *v) {
  expose(u);
  return expose(v);
}

inline bool connected(node *u, node *v)
{
    if (u == v)
        return true;

    node *a = expose(u);
    node *b = expose(v);

    return a->p != NULL;
}

int main() {

    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    int N, M;
    scanf("%d %d", &N, &M);

    while (M--)
    {
        int tip, a, b;

        scanf("%d %d %d ", &tip, &a, &b);

        if (tip == 1)
            link(pool + a, pool + b);
        else
             if (connected(pool + a, pool + b))
                puts("DA");
            else
                puts("NU");
    }

}