Cod sursa(job #3269736)

Utilizator schema_227Stefan Nicola schema_227 Data 20 ianuarie 2025 16:24:23
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream in("bile.in");
ofstream out("bile.out");

int dir_x[4] = {1, -1, 0, 0};
int dir_y[4] = {0, 0, 1, -1};

int n;
vector<pair<int,int>> steps;
vector<int> father, depth, compSize;

inline int getID(int r, int c)
{
    return (r - 1) * n + c;
}

int FindRoot(int x)
{
    if(father[x] == x) return x;
    return father[x] = FindRoot(father[x]);
}

void Union(int x, int y)
{
    int r1 = FindRoot(x);
    int r2 = FindRoot(y);
    if(r1 != r2)
    {
        if(depth[r1] < depth[r2])
        {
            father[r1] = r2;
            compSize[r2] += compSize[r1];
        }
        else if(depth[r1] > depth[r2])
        {
            father[r2] = r1;
            compSize[r1] += compSize[r2];
        }
        else
        {
            father[r2] = r1;
            compSize[r1] += compSize[r2];
            depth[r1]++;
        }
    }
}

int main()
{
    in >> n;
    steps.resize(n*n + 1);
    for(int i = 1; i <= n*n; i++)
    {
        in >> steps[i].first >> steps[i].second;
    }

    father.resize(n*n + 1);
    depth.resize(n*n + 1, 0);
    compSize.resize(n*n + 1, 1);
    for(int i = 1; i <= n*n; i++)
    {
        father[i] = i;
    }

    vector<vector<bool>> is_there(n+1, vector<bool>(n+1, false));
    vector<int> ans(n*n + 1, 0);
    int currentMax = 0;

    for(int i = 1; i <= n*n; i++)
    {
        int idx = n*n - i + 1;
        int r = steps[idx].first;
        int c = steps[idx].second;
        is_there[r][c] = true;
        int id = getID(r,c);

        for(int d = 0; d < 4; d++)
        {
            int rr = r + dir_x[d];
            int cc = c + dir_y[d];
            if(rr >= 1 && rr <= n && cc >= 1 && cc <= n && is_there[rr][cc])
            {
                Union(id, getID(rr, cc));
            }
        }
        int rootID = FindRoot(id);
        if(compSize[rootID] > currentMax)
        {
            currentMax = compSize[rootID];
        }
        ans[n*n - i] = currentMax;
    }

    for(int i = 1; i <= n*n; i++)
    {
        out << ans[i] << "\n";
    }
    return 0;
}