Cod sursă (job #786333)

Utilizator avatar Andrei_ierdnA Neculau Rares-Andrei Andrei_ierdnA IP ascuns
Problemă Burlane Compilator cpp-32 | 1,58 kb
Rundă Arhiva de probleme Status evaluat
Dată 15 sept. 2024 13:17:48 Scor 100
#include <fstream>

using namespace std;

ifstream f("burlane.in");
ofstream g("burlane.out");

const int MAXN = 100000;
const int BSIZE = 316;

int n, q, p[MAXN+BSIZE+2];
int bmap[MAXN+BSIZE+2];
int bjump[MAXN+BSIZE+2], bjumplen[MAXN+BSIZE+2];


void batogCalcBmap()
{
    for (int i = 1; (i-1) * BSIZE + 1 <= n; i++) {
        for (int j = (i-1) * BSIZE + 1; j <= i * BSIZE; j++) {
            bmap[j] = i;
        }
    }
}

void batogUpdateBucket(int bucket)
{
    for (int j = (bucket-1) * BSIZE + 1; j <= bucket * BSIZE; j++) {
        if (bmap[p[j]] < bmap[j]) {
            bjump[j] = p[j];
            bjumplen[j] = 1;
        }
        else {
            bjump[j] = bjump[p[j]];
            bjumplen[j] = bjumplen[p[j]] + 1;
        }
    }
}

int batogQueryPoz(int poz)
{
    int ans = 0;
    while (poz) {
        ans += bjumplen[poz];
        poz = bjump[poz];
    }
    return ans;
}

void batogInitAll()
{
    batogCalcBmap();
    for (int i = 1; i <= bmap[n]; i++) {
        batogUpdateBucket(i);
    }
}


void readData()
{
    f >> n >> q;
    for (int i = 1; i <= n; i++) {
        f >> p[i];
    }
}

void readAndSolveQueries()
{
    for (int i = 1; i <= q; i++) {
        int tip, x;
        f >> tip >> x;
        if (tip == 1) {
            g << batogQueryPoz(x) << '\n';
        }
        else {
            int y;
            f >> y;
            p[x] = y;
            batogUpdateBucket(bmap[x]);
        }
    }
}

int main()
{
    readData();
    batogInitAll();
    readAndSolveQueries();
    return 0;
}