Cod sursa(job #1771675)

Utilizator ducu34Albastroiu Radu Gabriel ducu34 Data 5 octombrie 2016 21:03:48
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.11 kb
//
//  main.cpp
//  Stramosi
//
//  Created by Albastroiu Radu on 10/5/16.
//  Copyright © 2016 Albastroiu Radu. All rights reserved.
//

#include <iostream>
#include <fstream>
#include <algorithm>
#include <unordered_map>
#include <vector>

using namespace std;

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

int i, j, n, m, x, y;
int dinamica[25][250001];

/* All you need to understand :

   d[i][j] = d[ d[i][j-1] ][j-1]
   i - element (node)
   j - distance (2^j)
   d[i][j] - parrent of i at 2^j distance */

int main()
{
    // read;
    fin >> n >> m;
    
    for(i=1;i<=n;i++)
        fin >> dinamica[0][i];
    
    // precompute dinamica
    for(j=1;j<=17;j++)
    {
        for(i=1;i<=n;i++)
        {
            dinamica[j][i] = dinamica[j-1][dinamica[j-1][i]];
        }
    }
    
    // computing the distance in log time
    for(i=1;i<=m;i++)
    {
        fin >> x >> y;
        j = 0;
        while(y)
        {
            if(y%2)
            {
                x = dinamica[j][x];
            }
            j++;
            y /= 2;
        }
        fout << x << "\n";
    }
    
    return 0;
}