Cod sursa(job #939939)

Utilizator dutzulBodnariuc Dan Alexandru dutzul Data 15 aprilie 2013 01:30:33
Problema Radiatie Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.03 kb
#include <fstream>
using namespace std;
ifstream f("radiatie.in");
ofstream g("radiatie.out");

#include <algorithm>
#include <vector>
#define pb push_back
#define mp make_pair
#define LE 30666

struct pii
{
    int x,y,z;
};
int i,n,m,k,xx,yy,le;
vector<int> Tree [LE];
int result[LE];
vector<pair<int,int> > qr[LE];
int viz[LE],lis[LE],color;
int father[LE],maxn;
int r1,r2,card[LE];
pii edge[LE];
int k2;

pii mk3(int v1,int v2,int v3)
{
    pii res;
    res.x=v1,res.y=v2,res.z=v3;
    return res;
}

bool comp(pii i1,pii i2)
{
    return i1.z<i2.z;
}

void dfs(int nod)
{
    int N=Tree[nod].size();
    viz[nod]=color;
    lis[++k]=nod;
    father[nod]=r1;

    for(int i=0; i<N; ++i)
        if (viz[Tree[nod][i]]!=color)
            dfs(Tree[nod][i]);
}

int  root(int nod1)
{
    while (nod1!=father[nod1])
        nod1=father[nod1];

    return nod1;
}

void unite(int nod1,int nod2)
{
    r1=root(nod1),r2=root(nod2);

    if (r1==r2) return;

    if (card[r1]>card[r2])
    {
        unite(nod2,nod1);
        return;
    }

    k=0,++color;
    dfs(r1);

    for(int i=1; i<=k; ++i)
    {
        int N=qr[lis[i]].size();

        for(int j=0; j<N; ++j)
        {
            pair<int,int> next=qr[lis[i]][j];

            if (result[next.second]==0)
                if (root(next.first)==r2)
                    result[next.second]=maxn;
        }
    }

    father[r1]=r2;
    Tree[r2].pb(r1);
    card[r2]+=card[r1];
}

int main()
{
    f>>n>>m>>k2;
    for(i=1; i<=m; ++i)
    {
        f>>xx>>yy>>le;
        edge[i]=mk3(xx,yy,le);
    }
    for(i=1; i<=k2; ++i)
    {
        f>>xx>>yy;
        qr[xx].pb(mp(yy,i));
        qr[yy].pb(mp(xx,i));
    }
    sort(edge+1,edge+m+1,comp);

    for(i=1; i<=n; ++i)
        father[i]=i;

    for(i=1; i<=m; ++i)
    {
        maxn=max(maxn,edge[i].z);
        unite(edge[i].x,edge[i].y);
    }


    for(i=1; i<=k2; ++i)
        g<<result[i]<<'\n';


    f.close();
    g.close();
    return 0;
}