Pagini recente » Cod sursa (job #90283) | Cod sursa (job #2845124) | Cod sursa (job #1406950) | Cod sursa (job #2305986) | Cod sursa (job #786238)
Cod sursa(job #786238)
#include <fstream>
#include <vector>
#include<algorithm>
using namespace std;
const int N=15001;
int v[N],T[N],D[N],lvl[N],drum[N],n,m;
struct muchie{int x,y,c;} q[2*N];
struct etc{int x,c;};
vector<etc> a[N];
bool use[N];
ifstream in("radiatie.in");
ofstream out("radiatie.out");
inline bool cmp(const muchie &a,const muchie &b)
{
return a.c<b.c;
}
int cap(int x)
{
if (T[x]==x)
return x;
return cap(T[x]);
}
inline void merge(int a,int b)
{
if (D[a]>D[b])
{
T[b]=a;
D[a]+=D[b];
}
else
{
T[a]=b;
D[b]+=D[a];
}
}
void dfs(int x,int L)
{
if (use[x])
return;
use[x]=true;
lvl[x]=L;
for (unsigned int i=0;i<a[x].size();i++)
{
int Y=a[x][i].x;
if (!use[Y])
{
dfs(Y,L+1);
drum[Y]=a[x][i].c;
T[Y]=x;
}
}
}
int lca(int x,int y)
{
int cost=0;
while(lvl[x]>lvl[y])
{
cost=max(cost,drum[x]);
x=T[x];
}
while (lvl[x]<lvl[y])
{
cost=max(cost,drum[y]);
y=T[y];
}
while (x!=y)
{
cost=max(cost,max(drum[x],drum[y]));
x=T[x];y=T[y];
}
return cost;
}
int main()
{
int i,t,x,y,A,B;
etc X;
in>>n>>m>>t;
for (i=1;i<=n;i++)
{
T[i]=i;
D[i]=1;
}
for (i=1;i<=m;i++)
in>>q[i].x>>q[i].y>>q[i].c;
sort(q+1,q+m+1,cmp);
for (i=1;i<=m;i++)
{
A=cap(q[i].x);
B=cap(q[i].y);
if (A!=B)
{
merge(A,B);
X.x=q[i].y;X.c=q[i].c;
a[q[i].x].push_back(X);
X.x=q[i].x;
a[q[i].y].push_back(X);
}
}
for (i=1;i<=n;i++)
if (T[i]==i)
{
dfs(i,1);
break;
}
while (t--)
{
in>>x>>y;
out<<lca(x,y)<<"\n";
}
return 0;
}