Cod sursa(job #2695026)

Utilizator andrei_ciobanuciobanu andrei andrei_ciobanu Data 11 ianuarie 2021 15:48:57
Problema Stramosi Scor 60
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.53 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <functional>

using namespace std;

#define MAX_PEOPLE 250001
#define MAX_TESTS 300001

struct test{
    int person, ancestorNumber;
};


int descendance[2][MAX_PEOPLE], ancestors[MAX_PEOPLE];
test tests[MAX_TESTS];
int sortedIndex[MAX_TESTS], ans[MAX_TESTS];

bool compare_tests(int a, int b){
    return tests[a].ancestorNumber<tests[b].ancestorNumber?true:false;
}

/*
void mysort(int v[], int left, int right){
    printf("entered function\n");
    int pivot = v[(left + right) / 2];
    int i1 = left, i2 = right;
    while (compare_tests(v[i1], pivot)) i1 ++;
    while (compare_tests(pivot, v[i2])) i2 --;
    while (i2 > i1){
        swap(v[i1], v[i2]);
        do i1 ++; while (compare_tests(v[i1], pivot));
        do i2 --; while (compare_tests(pivot, v[i2]));
    }
    if (left < i2) mysort(v, left, i2);
    if (i2 + 1 < right) mysort(v, i2 + 1, right);

}
*/

int main()
{
    FILE *fin=fopen("stramosi.in", "r");
    int peopleNo, testNo;
    fscanf(fin, "%d%d", &peopleNo, &testNo);

    int i;
    for (i=1; i<=peopleNo; i++){
        fscanf(fin, "%d", &ancestors[i]);
        descendance[1][i]=ancestors[i];
    }

    int maxAncestorNumber=0;
    for (i=1; i<=testNo; i++){
        sortedIndex[i]=i;
        fscanf(fin, "%d%d", &tests[i].person, &tests[i].ancestorNumber);
        if (maxAncestorNumber<tests[i].ancestorNumber) maxAncestorNumber=tests[i].ancestorNumber;
    }
    fclose(fin);

    //mysort(sortedIndex, 1, testNo);

    sort(sortedIndex+1, sortedIndex+testNo+1, compare_tests);

    int ancestorNumber=1, testIndex=1, ansIndex=1;
    while(tests[sortedIndex[testIndex]].ancestorNumber==ancestorNumber){
        ans[ansIndex++]=ancestors[tests[sortedIndex[testIndex++]].person];
    }

    ancestorNumber++;
    while (ancestorNumber<=maxAncestorNumber){
        int other=!(ancestorNumber&1);

        for (i=1; i<=peopleNo; i++){
            descendance[ancestorNumber&1][i]=ancestors[descendance[other][i]];
        }

        while(tests[sortedIndex[testIndex]].ancestorNumber==ancestorNumber){
            ans[ansIndex++]=descendance[ancestorNumber&1][tests[sortedIndex[testIndex++]].person];
        }
        ancestorNumber++;
    }

    for (i=1; i<=testNo; i++){
        tests[sortedIndex[i]].person=ans[i];
    }

    FILE *fout=fopen("stramosi.out", "w");
    for (i=1; i<=testNo; i++){
        fprintf(fout, "%d\n", tests[i].person);
    }
    fclose(fout);
    return 0;
}