Cod sursa(job #2753309)

Utilizator PatrickCplusplusPatrick Kristian Ondreovici PatrickCplusplus Data 22 mai 2021 13:08:56
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("jstc.in");
ofstream fout("jstc.out");

const int nmax = 1000005;
int a, b, x, cnt, tata[nmax], r[nmax], maxx[nmax];
bool isIn[nmax];
string q;
vector <int> v;

int getParent(int x){
    int nod = x;
    while (tata[nod] != nod){
        nod = tata[nod];
    }
    while (tata[x] != x){
        int aux = tata[x];
        tata[x] = nod;
        x = aux;
    }
    return nod;
}


void Union(int x, int y){
    int pX = getParent(x);
    int pY = getParent(y);
    if (pX == pY){
        return;
    }
    if (r[pX] < r[pY]){
        maxx[pY] = max(maxx[pY], maxx[pX]);
        tata[pX] = pY;
    }
    else{
        maxx[pX] = max(maxx[pX], maxx[pY]);
        tata[pY] = pX;
    }
}


int main(){
    fin >> a >> b >> q;
    long long ans = 0;
    for (int i = 1; i < nmax - 2; ++i){
        tata[i] = maxx[i] = i;
    }
    for (auto it : q){
        if (it == 'I'){
            ++cnt;
            v.push_back(cnt);
            isIn[cnt] = true;
        }
        else if (it == 'E'){
            isIn[v.back()] = false;
            Union(v.back(), cnt + 1);
            v.pop_back();
        }
        else{
            x = (1LL * a * x + b) % cnt + 1;
            int idk = getParent(x);
            idk = maxx[idk];
            if (isIn[idk]){
                ans += idk;
            }
            else{
                ans -= 1;
            }
        }
    }
    fout << ans;
    fin.close();
    fout.close();
    return 0;
}