Pagini recente » Cod sursa (job #40601) | Cod sursa (job #377286) | Cod sursa (job #2544168) | Cod sursa (job #51120) | Cod sursa (job #2278871)
#include <bits/stdc++.h>
using namespace std;
const int nmax=30005;
vector <pair <int, pair <int, int> > > v;
vector <pair <int, pair <int, int> > > rasp;
vector <pair <int, int> >g[nmax/2];
vector <pair <int, int> > t (nmax/2);
int depth[nmax/2];
bool visited[nmax];
int tata[nmax/2];
int tata_suprem(int i)
{
if(tata[i]==i)
return i;
return tata[i]=tata_suprem(tata[i]);
}
void add(int x, int y)
{
int k=tata_suprem(x);
int l=tata_suprem(y);
tata[l]=k;
}
bool cmp(pair <int, pair <int, int> > a, pair <int, pair <int, int> > b)
{
return a.first<b.first;
}
void dfs(int start_node)
{
visited[start_node]=true;
for(int i=0;i<g[start_node].size();i++)
{
if(visited[g[start_node][i].first]==false)
{
t[g[start_node][i].first].first=start_node;
t[g[start_node][i].first].second=g[start_node][i].second;
depth[g[start_node][i].first]=depth[start_node]+1;
dfs(g[start_node][i].first);
}
}
}
int lca(int x, int y)
{
int maxim1, maxim2;
maxim1=maxim2=-1;
while(depth[x]!=depth[y])
{
if(depth[x]>depth[y])
{
if(maxim1<t[x].second)
maxim1=t[x].second;
x=t[x].first;
}
else
{
if(maxim2<t[y].second)
maxim2=t[y].second;
y=t[y].first;
}
}
while(x!=y)
{
maxim1<t[x].second?maxim1=t[x].second:maxim1=maxim1;
x=t[x].first;
if(x==y)
{
if(maxim1>maxim2)
return maxim1;
return maxim2;
}
if(maxim2<t[y].second)
maxim2=t[y].second;
y=t[y].second;
}
if(maxim1>maxim2)
return maxim1;
return maxim2;
}
int main()
{
freopen("radiatie.in", "r", stdin);
freopen("radiatie.out", "w", stdout);
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
for(int i=1;i<=m;i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
v.push_back(make_pair(c, make_pair(a, b)));
}
sort(v.begin(), v.end(), cmp);
int curent, cnt_curent;
curent=0;
for(int cnt_curent=0;cnt_curent<n-1;curent++)
{
int x, y;
x=v[curent].second.first;
y=v[curent].second.second;
if(tata_suprem(x)==tata_suprem(y))
{
add(x, y);
rasp.push_back(v[curent]);
cnt_curent++;
}
}
for(int i=0;i<n-1;i++)
{
int x=rasp[i].second.first;
int y=rasp[i].second.second;
int cost=rasp[i].first;
g[x].push_back(make_pair(y, cost));
g[y].push_back(make_pair(x, cost));
}
dfs(1);
for(int i=1;i<=k;i++)
{
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", lca(x, y));
}
return 0;
}