Advertisement
juaniisuar

Problema A torneo N3 2014

Aug 31st, 2015
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #define forn(i,n) for(int i=0; i<n; i++)
  4. #define MAXN 17
  5.  
  6. using namespace std;
  7.  
  8. int ref[100000 + 100];
  9. int tree[(1<<MAXN) + 100];
  10.  
  11. int n, q;
  12.  
  13. int solve(int);
  14. int query(int, int);
  15.  
  16. int main()
  17. {
  18.     freopen("torneo.in", "r", stdin);
  19.     freopen("torneo.out", "w", stdout);
  20.     int x, y;
  21.  
  22.     cin >> n >> q;
  23.  
  24.     forn(i,(1<<n)){
  25.         cin >> x;
  26.         tree[(1<<(MAXN-1))+i] = x;
  27.         ref[x] = i+1;
  28.     }
  29.  
  30.     solve(1);
  31.  
  32.     cout << ref[ tree[1] ] << endl;
  33.  
  34.     forn(i,q){
  35.         cin >> x >> y;
  36.         cout << query(x,y) << endl;
  37.     }
  38.  
  39.     return 0;
  40. }
  41.  
  42. int query(int x, int y){
  43.     int round = 1;
  44.     int ind = (1<<(MAXN-1)) + x-1;
  45.     ind /= 2; //para que no tome la base de la piramide and boom
  46.  
  47.     if( x == y ) return 0;
  48.  
  49.     while( ind ){
  50.         if( (ref[tree[ind*2]]==y) || (ref[tree[ind*2+1]]==y) ) return round;
  51.  
  52.         round++;
  53.         ind /= 2;
  54.     }
  55.  
  56.     return 0;
  57. }
  58.  
  59. int solve(int ind){
  60.     int a, b;
  61.     if( ind >= (1<<(MAXN-1)) ) return tree[ind];
  62.  
  63.     a = (tree[ind*2]) ? tree[ind*2] : solve(ind*2);
  64.     b = (tree[ind*2+1]) ? tree[ind*2+1] : solve(ind*2+1);
  65.  
  66.     return tree[ind] = max(a,b);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement