Cod sursa(job #939940)

Utilizator dutzulBodnariuc Dan Alexandru dutzul Data 15 aprilie 2013 01:33:03
Problema Radiatie Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.06 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
#define sh short int

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

pii mk3(sh v1,sh 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)
{
    sh N=Tree[nod].size();
    viz[nod]=color;
    lis[++k]=nod;
    father[nod]=r1;

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

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

    return nod1;
}

void unite(sh nod1,sh 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(sh i=1; i<=k; ++i)
    {
        sh N=qr[lis[i]].size();

        for(sh j=0; j<N; ++j)
        {
            pair<sh,sh> 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;
}