Cod sursa(job #1064427)

Utilizator hrazvanHarsan Razvan hrazvan Data 21 decembrie 2013 20:27:39
Problema Stramosi Scor 100
Compilator c Status done
Runda Arhiva de probleme Marime 1.64 kb
#include <stdio.h>
#define NMAX 250000
#define MMAX 300000
typedef struct{
    int vf, next;
}lista;
typedef struct{
    int vf, dist, next, rez;
}quer;
lista v[2 * NMAX + 1];
int ult[NMAX + 1], ultq[NMAX + 1], lis[NMAX + 1], pozmax = 1;
char trecut[NMAX + 1];
quer  q[MMAX + 1];

inline void adaug(int k, int a, int b){
    v[k].vf = b;
    v[k].next = ult[a];
    ult[a] = k;
    return ;
}

void cautII(int x){
    trecut[x] = 1;
    int poz, y;
    poz = ultq[x];
    while(poz > 0){
        y = pozmax - q[poz].dist;
        if(y >= 1)   q[poz].rez = lis[y];
        else  q[poz].rez = 0;
        poz = q[poz].next;
    }

    poz = ult[x];
    lis[pozmax] = x;
    pozmax++;
    while(poz > 0){
        y = v[poz].vf;
        if(!trecut[y])  cautII(y);
        poz = v[poz].next;
    }
    lis[pozmax-1] = 0;
    pozmax--;
    return ;
}

void cautI(int x){
    while(v[x].next != 0)   x = v[x].next;
    cautII(x);
}

int main()
{
    FILE *in = fopen("stramosi.in", "r");
    int n, m;
    fscanf(in, "%d%d", &n, &m);
    int i, x, k = 0;
    for(i = 1; i <= n; i++){
        fscanf(in, "%d", &x);
        k++;
        adaug(k, i, x);
        k++;
        adaug(k, x, i);
    }
    int y;
    for(i = 1; i <= m; i++){
        fscanf(in, "%d%d", &x, &y);
        q[i].vf = x;
        q[i].dist = y;
        q[i].next = ultq[x];
        ultq[x] = i;
    }
    fclose(in);
    for(i = 1; i <= n; i++){
        if(!trecut[i])  cautI(i);
    }
    FILE *out = fopen("stramosi.out", "w");
    for(i = 1; i <= m; i++){
        fprintf(out, "%d\n", q[i].rez);
    }
    fclose(out);
    return 0;
}