Cod sursa(job #757965)

Utilizator XladhenianGrigorita Vlad-Stefan Xladhenian Data 13 iunie 2012 22:47:57
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.79 kb

#include <fstream>
#include <stdlib.h>
#include <string.h>
using namespace std;

long N,M;
long A[260000];

long P[19][260000];

long ReadInt(char *&S)
{
 while ((*S) < '0')
  {
   S += 1;
  }
 long Res = 0;
 while ((*S) >= '0')
  {
   Res = (Res * 10) + ((*S) - '0');
   S += 1;
  }
 return Res;
}

void WriteInt(char *&S,long long n)
{
 if (n == 0)
   {
    S[0] = '0';
    S[1] = ' ';
    S += 2;
    return;
   }
 char Data[40];
 long i = 0;
 while (n > 0)
  {
   Data[i] = (n % 10) + '0';
   n /= 10;
   i += 1;
  }
 for (i -= 1;i >= 0;i -= 1)
  {
   (*S) = Data[i];
   S += 1;
  }
 (*S) = ' ';
 S += 1;  
}

char Input[6000000];
char Output[2000000];
char *InPos;
char *OutPos;

void ReadInput(void)
{
 FILE *FIN = fopen("stramosi.in","rt");
 fseek(FIN,0,SEEK_END);
 long SS = ftell(FIN);
 fseek(FIN,0,SEEK_SET);
 fread(Input,1,SS,FIN);
 fclose(FIN);
}

void WriteOutput(void)
{
 FILE *FOUT = fopen("stramosi.out","wt");
 fwrite(Output,1,OutPos - Output,FOUT);
 fclose(FOUT);
}

void Compute(void)
{
 long i,j;
 for (i = 1;i <= N;i += 1)
  {
   P[0][i] = A[i];
  }
 for (i = 1;i < 19;i += 1)
  {
   for (j = 1;j <= N;j += 1)
    {
     P[i][j] = P[i - 1][P[i - 1][j]];
    }
  }
}

long Cauta(long Q,long C)
{
 long mm = 18;
 long c = Q;
 while (mm >= 0)
  {
   if ((C & (1 << mm)) == (1 << mm))
     {
      c = P[mm][c];
     }
   mm -= 1;
  }
 return c;
}

int main(void)
{
 ReadInput();
 InPos = Input;
 OutPos = Output;
 long i,j,a,b;
 N = ReadInt(InPos);
 M = ReadInt(InPos);
 for (i = 1;i <= N;i += 1)
  {
   A[i] = ReadInt(InPos);
  }
 Compute();
 for (i = 0;i < M;i += 1)
  {
   a = ReadInt(InPos);
   b = ReadInt(InPos);
   WriteInt(OutPos,Cauta(a,b));
  }
 WriteOutput();
 return 0;
}