Cod sursa(job #2134281)

Utilizator FrequeAlex Iordachescu Freque Data 17 februarie 2018 20:05:40
Problema Jocul Flip Scor 0
Compilator cpp Status done
Runda wellcode Marime 1.93 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 1000 + 5;

vector <int> vf[NMAX];
int n, k;
int rang[NMAX], father[NMAX];
bool vis[NMAX];

int find_root(int x)
{
    int i;
    for (i = x; i != father[i]; i = father[i]);

    while (x != father[x])
    {
        int y = father[x];
        father[x] = i;
        x = y;
    }

    return i;
}

void unite(int x, int y)
{
    x = find_root(x);
    y = find_root(y);

    if (rang[x] > rang[y])
    {
        rang[x] += rang[y];
        father[y] = x;
    }
    else
    {
        rang[y] += rang[x];
        father[x] = y;
    }
}

void write()
{
    for (int i = 1; i <= n; ++i)
    {
        if (!vis[father[i]])
        {
            vis[father[i]] = true;
            for (int j = i; j <= n; ++j)
                if (father[i] == father[j])
                    fout << j << " ";
            fout << '\n';
        }
    }
}

void read()
{
    int x;

    fin >> n >> k;

    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= k; ++j)
        {
            fin >> x;
            if (vf[x].empty() || i != vf[x][vf[x].size() - 1])
                vf[x].push_back(i);

            rang[i] = 1;
            father[i] = i;
        }
}

int main()
{
    read();

    for (int i = 0; i <= 1000; ++i)
        if (vf[i].size() > 1)
            for (int j = 0; j == 0 || j < vf[i].size(); ++j)
                if (j < vf[i].size() - 1)
                {
                    unite(vf[i][j], vf[i][j + 1]);
                }

    write();

    return 0;
}

// Solutie O(n^4): iau fiecare pereche de fete si compar fiecare din numerele lor - brute force
// Solutie O(n^3 * log*n): unesc cu paduri de multimi disjuncte
// Solutie O(n^2 + n * log* + n^2): vector de aparitii ale florilor + paduri de multimi disjuncte + afisare