Cod sursa(job #2394086)

Utilizator alexandruilieAlex Ilie alexandruilie Data 1 aprilie 2019 12:15:20
Problema Radiatie Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.64 kb
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
ifstream f("radiatie.in");
ofstream g("radiatie.out");
vector <int> gp[15005];
struct muchie {int x,y,c;}mu[30005];
int t[15005],h[15005],v[15005],n,m,k,i,j,x,y,x1,y1;
int root(int nod)
{
    while(t[nod]!=nod) nod=t[nod];
    return nod;
}
int cmp(muchie a,muchie b)
{
    return a.c<b.c;
}
void  df(int nod)
{
    int i,vec;
    h[nod]++;
    for(i=0;i<gp[nod].size();++i)
    {
        vec=gp[nod][i];
        df(vec);
    }
}
void unite(int i,int j,int c)
{
    if(h[i]<h[j])
    {
        t[i]=j;
        v[i]=c;
        gp[j].push_back(i);
        df(i);
    }
    else
    if(h[i]>h[j])
    {
        t[j]=i;
        v[j]=c;
        gp[i].push_back(j);
        df(j);
    }
    else
    {
        h[j]++;
        t[j]=i;
        v[j]=c;
        gp[i].push_back(j);
        df(j);
    }

}
int query(int x,int y)
{
    int ans=0;
    while(h[x]>h[y])
    {
        ans=max(ans,v[x]);
        x=t[x];
    }

    while(h[x]<h[y])
    {
        ans=max(ans,v[y]);
        y=t[y];
    }
    while(x!=y)
    {
        ans=max(v[x],v[y]);
        x=t[x];
        y=t[y];
    }
    return ans;
}
int main()
{
    f>>n>>m>>k;
    for(i=1;i<=m;i++)
        f>>mu[i].x>>mu[i].y>>mu[i].c;
    sort(mu+1,mu+m+1,cmp);
    for(i=1;i<=n;i++) t[i]=i;
    i=0;j=1;
    while(i<n-1)
    {
        x1=root(mu[j].x);
        y1=root(mu[j].y);
        if(x1!=y1)
            unite(x1,y1,mu[j].c),i++;
        j++;
    }
    for(i=1;i<=k;i++)
    {
        f>>x>>y;
        g<<query(x,y)<<'\n';
    }
    return 0;
}