Cod sursa(job #1408983)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 30 martie 2015 12:48:13
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <cstdio>
#include <algorithm>

const int N = 100000 + 10;

int n;

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

node pool[N];

inline void node::relax() {
  if (rev) {
    if (ch[0]) ch[0]->rev ^= 1;
    if (ch[1]) ch[1]->rev ^= 1;
    std::swap(ch[0], ch[1]);
    rev = 0;
  }
}

inline void rotate(node *u) {
  node *v = u->p;
  v->relax(), u->relax();
  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) {
  u->relax();
  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 evert(node *u) {
  expose(u)->rev ^= 1;
  splay(u);
}

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

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

inline bool connected(node *u, node *v) {
  evert(u);
  evert(v);
  return !u->isroot();
}
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");
    }

}