Cod sursa(job #684764)

Utilizator mihai995mihai995 mihai995 Data 20 februarie 2012 20:48:47
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <vector>
using namespace std;

const int N=10005,M=100005,inf=1<<30;
int v[M],dist[N],cost[N],n;
bool use[N];
struct Muchie
{
    int y,c;
};
vector<Muchie> a[N];

ifstream in("apm2.in");
ofstream out("apm2.out");

inline bool cmp(int a,int b)
{
    return dist[a]<dist[b];
}

inline void sch(int &a,int &b)
{
    int c=a;a=b;b=c;
}

void up(int x)
{
    if (x>1 && cmp(v[x],v[x>>1]))
    {
        sch(v[x],v[x>>1]);
        up(x>>1);
    }
}

void down(int x)
{
    int m=x,S=x<<1,D=S+1;
    if (S<=v[0] && cmp(v[S],v[m]))
        m=S;
    if (D<=v[0] && cmp(v[D],v[m]))
        m=D;
    if (m!=x)
    {
        sch(v[x],v[m]);
        down(m);
    }
}

void push(int x)
{
    v[++v[0]]=x;
    up(v[0]);
}

void pop(int &x)
{
    x=v[1];
    v[1]=v[v[0]--];
    down(1);
}


void prim(int x)
{
    int y,c;
    for (int i=1;i<=n;i++)
        dist[i]=inf;
    push(x);
    while (v[0])
    {
        pop(x);
        if (use[x])
            continue;
        use[x]=true;
        for (vector<Muchie>::iterator i=a[x].begin();i!=a[x].end();i++)
        {
            y=(*i).y;c=(*i).c;
            if (dist[y]>c)
            {
                dist[y]=c;
                cost[y]=max(cost[x],c);
                push(y);
            }
        }
    }
}

int main()
{
    int m,x,y,c,q;
    in>>n>>m>>q;
    while (m--)
    {
        in>>x>>y>>c;
        a[x].push_back((Muchie){y,c});
        a[y].push_back((Muchie){x,c});
    }
    prim(1);
    while (q--)
    {
        in>>x>>y;
        out<<max(cost[x],cost[y])-1<<"\n";
    }
    return 0;
}