Cod sursa(job #1523451)

Utilizator andrei_diaconuAndrei Diaconu andrei_diaconu Data 12 noiembrie 2015 19:06:32
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.5 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <string.h>

#define NMax 100010

using namespace std;

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

int nodes, edges, queries, disTree[10010], root;
vector <int> apm[10010];
struct edge {
    int node1;
    int node2;
    int cost;
} G[NMax];

struct apmStruct {
    int cost;
    int level;
    int father;
} apms[NMax];

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

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

void disUnion(int parent, int son, int upCost)
{
    disTree[parent] += disTree[son];
    disTree[son] = parent;
    
    root = parent;
    apm[parent].push_back(son);
    apms[son].cost = upCost;
    apms[son].father = parent;
}

void DFS(int node, int level)
{
    apms[node].level = level;
    for (vector<int>::iterator it = apm[node].begin(); it != apm[node].end(); it++)
        DFS(*it, level + 1);
}

int main()
{
    f >> nodes >> edges >> queries;
    
    for (int i=1; i<=edges; i++)
        f >> G[i].node1 >> G[i].node2 >> G[i].cost;
    
    sort (G+1, G+edges+1, cmp);
    
    for (int i=1; i<=nodes; i++)
        disTree[i] = -1;
    
    int nEdge = 0, elem = 1;
    
    while (elem < nodes) {
        nEdge++;
        edge crtEdge;
        crtEdge.node1 = G[nEdge].node1;
        crtEdge.node2 = G[nEdge].node2;
        crtEdge.cost = G[nEdge].cost;
        
        int father1 = findFather(crtEdge.node1);
        int father2 = findFather(crtEdge.node2);
        
        if (father1 != father2) {
            if (-disTree[father1] > -disTree[father2])
                disUnion(father1, father2, crtEdge.cost);
            else
                disUnion(father2, father1, crtEdge.cost);
            
            elem++;
        }
    }
    
    DFS(root, 1);
    
    int node1, node2;
    for (int i=1; i<=queries; i++) {
        f>>node1>>node2;
        
        int Max = -1;
        
        while (apms[node1].level > apms[node2].level)
            node1 = apms[node1].father;
        
        while (apms[node2].level > apms[node1].level)
            node2 = apms[node2].father;
        
        while (node1 != node2) {
            if (Max < apms[node1].cost)
                Max = apms[node1].cost;
            if (Max < apms[node2].cost)
                Max = apms[node2].cost;
            
            node1 = apms[node1].father;
            node2 = apms[node2].father;
        }
        
        g << Max-1 << "\n";
    }
    
    return 0;
}