Cod sursa(job #1945951)

Utilizator BugirosRobert Bugiros Data 29 martie 2017 19:49:49
Problema Radiatie Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.28 kb
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;

const int MAXN = 15003;
const int MAXM = 30000;

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

int n,m,k;

struct muchie
{
    int a,b,c;
};
muchie mch[MAXM];

bool ordine_buna(muchie a, muchie b)
{
    return a.c < b.c;
}

int tata[MAXN];
int costtata[MAXN];//costul muchiei care duce la tata
int rang[MAXN];

vector<int> fii[MAXN];

int grupa(int x)
{
    while(tata[x] != x)
        x = tata[x];
    return x;
}

void reunire(int x, int y, int c)
{
    x = grupa(x);
    y = grupa(y);
    if (rang[x] < rang[y])
    {
        tata[x] = y;
        fii[y].push_back(x);
        costtata[x] = c;
    }
    if (rang[x] > rang[y])
    {
        tata[y] = x;
        fii[x].push_back(y);
        costtata[y] = c;
    }
    if (rang[x] == rang[y])
    {
        tata[y] = x;
        fii[x].push_back(y);
        costtata[y] = c;
        ++rang[x];
    }
}

void citire()
{
    in >> n >> m >> k;
    for (int i = 1;i <= m;++i)
        in >> mch[i].a >> mch[i].b >> mch[i].c;
}

void apm()
{
    sort (mch + 1, mch + m + 1,ordine_buna);
    for (int i = 1;i <= n;++i)
    {
        tata[i] = i;
        rang[i] = 1;
    }
    int nrmuchii = 0;
    for (int i = 1;nrmuchii < n - 1;++i)
    {
        int x = mch[i].a;
        int y = mch[i].b;
        int c = mch[i].c;
        if (grupa(x) != grupa(y))
        {
            reunire(x,y,c);
            ++nrmuchii;
        }
    }
}

int nivel[MAXN];

void dfs(int nod)
{
    for(unsigned int i = 0;i < fii[nod].size();++i)
    {
        nivel[fii[nod][i]] = nivel[nod] + 1;
        dfs(fii[nod][i]);
    }
}

int main()
{
    citire();
    apm();
    for (int i = 1;i <= n;++i)
        if (tata[i] == i)//radacina
            dfs(i);
    while(k > 0)
    {
        int x,y;
        in >> x >> y;
        int cmax = -1;
        while(x != y)
            if (nivel[x] > nivel[y])
            {
                cmax = max(cmax,costtata[x]);
                x = tata[x];
            }
            else
            {
                cmax = max(cmax,costtata[y]);
                y = tata[y];
            }
        out << cmax << '\n';
        --k;
    }
    return 0;
}