Cod sursă (job #786332)

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:16:45 Scor 0
#include <iostream>

using namespace std;

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()
{
    cin >> n >> q;
    for (int i = 1; i <= n; i++) {
        cin >> p[i];
    }
}

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

int main()
{
    cin.tie(NULL)->sync_with_stdio(false);
    readData();
    batogInitAll();
    readAndSolveQueries();
    return 0;
}