Cod sursa(job #777354)

Utilizator badmanDragan Dan badman Data 12 august 2012 00:51:42
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.15 kb
#include <cassert>
#include <cstdio>
#include <cstdlib>

#define n1max 250002
#define n2max 18

char *buffer;
int D[n2max + 1][n1max + 1];

void read(int &x ) {
    while (*buffer < '0' || *buffer > '9') 
        ++buffer;
    
    x = 0;
    while(*buffer >= '0' && *buffer <= '9') {
        x = x * 10 + *buffer - '0';
        ++buffer;
    }
}

int main(){
    int n, m, fs, i, j;
    FILE *input = fopen("stramosi.in", "r");
    FILE *output = fopen("stramosi.out", "w");

    fseek(input, 0, SEEK_END);
    fs = ftell(input);
    rewind(input);
    buffer = (char*)malloc(fs);
    assert(fread(buffer, 1, fs, input));
    fclose(input);
    
    read(n);
    read(m);
    for(i = 1; i <= n; ++i) 
        read(D[0][i]);
   
    for(i = 1; (1 << i) <= n; ++i) 
       for(j = 1; j <= n; ++j)
            D[i][j] = D[i - 1][D[i - 1][j]];
          
    while(m) {
        int x, y;
        read(x);
        read(y);

        for(i = 0; (1 << i) <= y; ++i)
            if((1 << i) & y)
                x = D[i][x];
            
        fprintf(output, "%d\n", x);
        m--;
    }
    fclose(output);

    return 0;
}