Cod sursa(job #1517569)

Utilizator GinguIonutGinguIonut GinguIonut Data 4 noiembrie 2015 16:30:05
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.49 kb
#include <fstream>
#include <vector>
#include <algorithm>
#define nMax 15005
#define mMax 30005
using namespace std;
ifstream fin("radiatie.in");
ofstream fout("radiatie.out");
int t[nMax], dist[nMax], Lev[nMax], n, m, q, a, b, i, tp, val1, val2;
vector<int> G[nMax];
struct muchii
{
    int a;
    int b;
    int c;
}Edge[mMax];
int cmp(muchii o, muchii p)
{
    return o.c<p.c;
}
int getRoot(int node)
{
    while(t[node])
        node=t[node];
    return node;
}
void DFS(int node, int lvl)
{
    Lev[node]=lvl;
    for(vector<int>::iterator it=G[node].begin();it!=G[node].end();it++)
        DFS(*it, lvl+1);

}
int LCA(int a, int b)
{
    int Max=0;
    if(Lev[b]>Lev[a])
        swap(a, b);
    while(Lev[a]>Lev[b])
    {
        Max=max(Max, dist[a]);
        a=t[a];
    }
    while(a!=b)
    {
        Max=max(Max, max(dist[a], dist[b]));
        a=t[a];
        b=t[b];
    }
    return Max;
}
int main()
{
    fin>>n>>m>>q;
    for(i=1;i<=m;i++)
        fin>>Edge[i].a>>Edge[i].b>>Edge[i].c;
    sort(Edge+1, Edge+m+1, cmp);
    tp=n-1;
    for(i=1;i<=m&&tp!=0;i++)
    {
        val1=getRoot(Edge[i].a);
        val2=getRoot(Edge[i].b);
        if(val1!=val2)
        {
            t[val1]=val2;
            G[val2].push_back(val1);
            dist[val1]=Edge[i].c;
            tp--;
        }
    }
    for(i=1;t[i];i++);
    DFS(i, 1);
    for(i=1;i<=q;i++)
    {
        fin>>a>>b;
        fout<<LCA(a, b)<<'\n';
    }
    return 0;
}