Cod sursa(job #2394080)

Utilizator cicero23catalin viorel cicero23 Data 1 aprilie 2019 12:08:06
Problema Radiatie Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.65 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#define Nmax 15001
using namespace std;
ifstream f("radiatie.in");
ofstream g("radiatie.out");
int t[Nmax],h[Nmax],n,m,k,val[Nmax];
vector <pair<int,pair<int,int> > >v;
int comp(pair<int,pair<int,int> > A,pair<int,pair<int,int> > B)
{
    return A.first<B.first;
}
int cauta(int x)
{
    while(t[x]!=0) x=t[x];
    return x;
}
void unire(int x,int y,int cost)
{
    int c;
    if(h[x]>h[y]){t[y]=x;c=x;val[y]=cost;}
    else {t[x]=y;c=y;val[x]=cost;}
    if(h[x]==h[y]) h[c]++;
}
int caut(int x)
{
    int t2=1;
    while(t[x]!=0) {x=t[x],t2++;}
    return t2;
}
int main()
{
    int i,x,y,c;
    f>>n>>m>>k;
    for(i=1;i<=n;i++)
    {
        h[i]=1;
    }
    for(int i=1;i<=m;i++)
    {
        f>>x>>y>>c;
        v.push_back({c,{x,y}});
    }
    sort(v.begin(),v.end(),comp);
    for(i=0;i<m;i++)
    {
        x=v[i].second.first;
        y=v[i].second.second;
        c=v[i].first;
        x=cauta(x);
        y=cauta(y);
        if(x!=y) unire(x,y,c);
    }
    for(i=1;i<=k;i++)
    {
        f>>x>>y;
        int h1=caut(x);
        int h2=caut(y);
        int maxi=0;
        while(h1>h2)
        {
            if(val[x]>maxi) maxi=val[x];
            h1--;
            x=t[x];
        }
        while(h2>h1)
        {
            if(val[y]>maxi) maxi=val[y];
            h2--;
            y=t[y];
        }
        while(x!=y)
        {
            if(val[y]>maxi) maxi=val[y];
            if(val[x]>maxi) maxi=val[x];
             x=t[x];
             y=t[y];
        }
        g<<maxi<<'\n';
    }
    return 0;
}