Cod sursa(job #2696410)

Utilizator teochess2017Togan Teodor-Bogdan teochess2017 Data 15 ianuarie 2021 20:49:32
Problema Stramosi Scor 100
Compilator c-64 Status done
Runda Arhiva de probleme Marime 1.52 kb
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define NMAX 250000
#define LOGN 20

int mat[NMAX][LOGN], v[NMAX];

FILE *fin, *fout;

struct pow{///am complicat putin codul cu structuri ca sa exersez lucrul pe ele
  int put, exp;
};

int readInt(){
  int n;
  char ch;
  while(!isdigit(ch = fgetc(fin)));
  n = ch - '0';
  while(isdigit(ch = fgetc(fin))){
    n = n * 10 + ch - '0';
  }
  return n;
}
struct pow closestpower(int a){
  struct pow putere;
  putere.put = 1;
  putere.exp = 0;
  while(putere.put <= a){
    putere.put *= 2;
    putere.exp++;
  }
  putere.put /= 2;
  putere.exp--;
  return putere;
}

int main()
{
    struct pow putere;
    int n, m, i, j, nextval, q, p;
    fin = fopen("stramosi.in", "r");
    n = readInt();
    m = readInt();
    for(i = 0; i < n; i++){
      v[i] = readInt();
      v[i]--;
    }
    for(i = 0; i < n; i++){
      for(j = 0; j < LOGN; j++){
        mat[i][j] = -1;
      }
    }
    for(i = 0; i < n; i++){
      nextval = v[i];
      j = 0;
      while(nextval != -1){
        mat[i][j] = nextval;
        nextval = mat[nextval][j];
        j++;
      }
    }
    fout = fopen("stramosi.out", "w");
    for(i = 0; i < m; i++){
      q = readInt();
      p = readInt();
      q--;
      while((0 < p) && (0 <= q)){
        putere = closestpower( p );
        q = mat[q][putere.exp];
        p -= putere.put;
      }
      fprintf(fout, "%d\n", q + 1);
    }
    fclose(fin);
    fclose(fout);
    return 0;
}