Cod sursa(job #1517326)

Utilizator andrei_diaconuAndrei Diaconu andrei_diaconu Data 4 noiembrie 2015 08:20:08
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.14 kb
#include <fstream>
#include <vector>
#include <algorithm>

#define NMax 15010

using namespace std;

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

using namespace std;

int nodes, edges, queries, disTree[NMax];
vector< int > apm[NMax];
bool mark[NMax];

struct edge {
    int ext1;
    int ext2;
    int cost;
} G[30010];

struct mnode {
    int level;
    int father;
}arbStruct[NMax];

bool cmp(const edge &e1, const edge &e2)
{
    return e1.cost < e2.cost;
}

void DFS(int node, int level)
{
    mark[node] = true;
    for (vector<int>::iterator it = apm[node].begin(); it != apm[node].end(); it++) {
        if (!mark[*it]) {
            arbStruct[*it].level = level;
            arbStruct[*it].father = node;

            DFS(*it, level+1);
        }
    }
}

int findFather(int node)
{
    while (disTree[node] > 0)
        node = disTree[node];

    return node;
}

int main()
{
    f>>nodes>>edges>>queries;

    for (int i=1; i<=edges; i++)
        f>>G[i].ext1>>G[i].ext2>>G[i].cost;
    for (int i=1; i<=nodes; i++)
        disTree[i] = -1;

    sort (G+1, G+edges+1, cmp);

    for (int i=1; i<=nodes-1; i++)
    {
        int father1 = findFather(G[i].ext1);
        int father2 = findFather(G[i].ext2);

        if (father1 != father2) {
            if (-father1 > -father2) {
                disTree[father1] += disTree[father2];
                disTree[father2] = father1;
            }
            else {
                disTree[father2] += disTree[father1];
                disTree[father1] = father2;
            }

            apm[G[i].ext1].push_back(G[i].ext2);
            apm[G[i].ext2].push_back(G[i].ext1);
        }
    }

    DFS(1, 0);

    int x, y;
    for (int i=1; i<=queries; i++) {
        f>>x>>y;

        while (arbStruct[x].level > arbStruct[y].level)
            x = arbStruct[x].father;
        while (arbStruct[x].level < arbStruct[y].level)
            y = arbStruct[y].father;

        while (x != y) {
            x = arbStruct[x].father;
            y = arbStruct[y].father;
        }

        g << x << "\n";
    }

    return 0;
}