Cod sursa(job #1501430)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 13 octombrie 2015 13:53:49
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.28 kb
#include <cstdio>
#include <cctype>

using namespace std;

const int Nmax = 250000 + 1;
const int lgMax = 18;
const int Buffmax = 65536;

char buffer[Buffmax];
int buffPtr = Buffmax;

inline char GetChar() {
    if (buffPtr == Buffmax) {
        fread(buffer, 1, Buffmax, stdin);
        buffPtr = 0;
    }
    return buffer[buffPtr++];
}

inline int ReadInt() {
    int q = 0;
    char c;

    do {
        c = GetChar();
    } while (!isdigit(c));
    do {
        q = (10 * q) + (c - '0');
        c = GetChar();
    } while (isdigit(c));
    return q;
}

int d[lgMax][Nmax];

int main(void) {
    freopen("stramosi.in", "r", stdin);
    freopen("stramosi.out", "w", stdout);
    int n, m;
    int u, k;

    n = ReadInt(); m = ReadInt();
    for (int i = 1; i <= n; i++) {
        d[0][i] = ReadInt();
    }

    for (int i = 1; (1 << i) <= n; i++) {
        for (int j = 1; j <= n; j++) {
            d[i][j] = d[i - 1][d[i - 1][j]];
        }
    }

    for (int i = 0; i < m; i++) {
        u = ReadInt(); k = ReadInt();
        for (int i = 0; (1 << i) <= k; i++) {
            if ((k >> i) & 1) {
                u = d[i][u];
            }
        }
        printf("%d\n", u);
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}