Cod sursa(job #1521057)

Utilizator papinubPapa Victor papinub Data 9 noiembrie 2015 21:11:13
Problema Stramosi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.55 kb
# include <cstdio>
using namespace std;
FILE *f=freopen("stramosi.in","r",stdin);
FILE *g=freopen("stramosi.out","w",stdout);
const int NMAX= 250001;
const int bufferDIM= 10001;
class inputReader{

    char buffer[bufferDIM];

public:

    int pos=0;

    bool digit(char &c)
    {
        return ('0'<=c && c<='9');
    }

    void getbuffer()
    {
        fread(buffer,1,bufferDIM,stdin);
        pos=0;
    }
    void getINT(int &numar)
    {
        numar=0;

        while (!digit(buffer[pos]))
        {
            if (++pos==bufferDIM)
                getbuffer();
        }

        while (digit(buffer[pos]))
        {
            numar=numar*10 + buffer[pos] - '0';
            if (++pos==bufferDIM)
                getbuffer();
        }
    }
}cin;
int n,m;
int a[20][NMAX];
int lg[NMAX];
void read()
{
    cin.getbuffer();
    cin.getINT(n);
    cin.getINT(m);
    for (int i=1;i<=n;i++) cin.getINT(a[0][i]);
}

void solve()
{
    for (int i=1;i<=n;i*=2)
    {
        for (int j=1;j<=n;j++)
        {
            a[i][j]=a[i-1][a[i-1][j]];
        }
    }
}

void query()
{
    int x,y;
    for (int i=1;i<=m;i++)
    {
            cin.getINT(x);
            cin.getINT(y);
            int p=0;
            while (y)
            {
                if (y&1)
                {
                    x=a[p][x];
                }
                y/=2;
                p++;
            }
            printf("%d\n",x);
    }
}
int main()
{
    read();
    solve();
    query();
    return 0;
}