Cod sursa(job #682503)

Utilizator dandroidDan Octavian dandroid Data 19 februarie 2012 02:38:37
Problema Lowest Common Ancestor Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
using namespace std;

#include <set>
#include <map>
#include <list>
#include <deque>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <utility>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>

#define oo (1<<30)
#define f first
#define s second
#define II inline
#define db double
#define ll long long
#define pb push_back
#define mp make_pair
#define Size(V) ((ll)(V.size()))
#define all(V) (V).begin() , (V).end()
#define CC(V) memset((V),0,sizeof((V)))
#define CP(A,B) memcpy((A),(B),sizeof((B)))
#define FOR(i,a,b) for(ll (i)=(a);(i)<=(b);++(i))
#define REP(i, N) for (ll (i)=0;(i)<(ll)(N);++(i))
#define FORit(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); ++it)
#define printll(x) printf("%lld",(x))
#define printsp() printf(" ")
#define newline() printf("\n")
#define readll(x) scanf("%lld",&(x))
#define debugll(x) fprintf(stderr,"%lld\n",(x))

#define IN "lca.in"
#define OUT "lca.out"

//#define ONLINE_JUDGE

const int MAX_NODES = 100100;

bool isIn[MAX_NODES];
int parent[MAX_NODES];

int nodeCount = 0;
int pairCount; 

int findCommon(int node)
{
  int ancestor = node; 
  while (!isIn[ancestor])
  {
    ancestor = parent[ancestor];
  } 
  return ancestor;
}

void markAncestors(int node, bool mark)
{
  int ancestor = node;
  while (true)
  {
    isIn[ancestor] = mark;
    if (ancestor == 1) break;
    ancestor = parent[ancestor];
  }
}

void lca(int n1, int n2)
{
  markAncestors(n1, true);
  int lca = findCommon(n2);
  markAncestors(n1, false);
  cout << lca << endl;
}

void solve(int test) {
  cin >> nodeCount >> pairCount; 
  for (int i = 2; i <= nodeCount; i++)
  {
    cin >> (parent[i]);
  } 
  int n1;
  int n2;
  for (int i = 0; i < pairCount; i++)
  {
    cin >> n1 >> n2;
    lca(n1, n2);
  }
}

int main() {
#ifndef ONLINE_JUDGE
  freopen(IN,"r",stdin);
  freopen(OUT,"w",stdout);
#endif
    solve(1);
  return 0;
}