Pagini recente » Cod sursa (job #1100361) | Cod sursa (job #300391) | Cod sursa (job #2791992) | Cod sursa (job #1144581) | Cod sursa (job #3282402)
#include <bits/stdc++.h>
using namespace std;
int tata[100005], height[100005];
void reset(int n) {
for (int i = 1; i <= n; i++) {
tata[i] = i;
height[i] = 1;
}
}
int getRoot(int x) {
int root = x;
while (root != tata[root]) {
root = tata[root];
}
// compresia drumurilor
while (x != root) {
int tx = tata[x];
tata[x] = root;
x = tx;
}
return root;
}
void unite(int x, int y) {
x = getRoot(x);
y = getRoot(y);
if (height[x] < height[y]) {
tata[x] = y;
} else if (height[x] > height[y]) {
tata[y] = x;
} else { // egalitate
tata[y] = x;
height[x] += 1;
}
}
vector <pair <int, pair <int, int>>> edges;
vector <pair <int, int>> graph[100005];
int neigh[20][100005];
int costs[20][100005];
int heights[100005];
void dfs(int node, int parent, int cost) {
neigh[0][node] = parent;
costs[0][node] = cost;
heights[node] = heights[parent] + 1;
for (auto x : graph[node]) {
if (x.first == parent) continue;
dfs(x.first, node, x.second);
}
}
int getMaxCost(int x, int y) {
int maximumCost = 0;
if (heights[x] < heights[y]) {
swap(x, y);
}
int difference = heights[x] - heights[y];
for (int p = 0; p < 20; ++p) {
if (difference & (1 << p)) {
maximumCost = max(maximumCost, costs[p][x]);
x = neigh[p][x];
}
}
if (x == y) return maximumCost;
for (int p = 19; p >= 0; --p) {
if (neigh[p][x] != neigh[p][y]) {
maximumCost = max(maximumCost, costs[p][x]);
maximumCost = max(maximumCost, costs[p][y]);
x = neigh[p][x];
y = neigh[p][y];
}
}
maximumCost = max(maximumCost, costs[0][x]);
maximumCost = max(maximumCost, costs[0][y]);
return maximumCost;
}
int main()
{
freopen("radiatie.in", "r", stdin);
freopen("radiatie.out", "w", stdout);
int n, m, k;
cin >> n >> m >> k;
reset(n);
for (int i = 1; i <= m; ++i) {
int x, y, c;
cin >> x >> y >> c;
edges.push_back(make_pair(c, make_pair(x, y)));
}
sort(edges.begin(), edges.end());
for (auto edge: edges) {
if (getRoot(edge.second.second) == getRoot(edge.second.first)) continue;
graph[edge.second.first].push_back({edge.second.second, edge.first});
graph[edge.second.second].push_back({edge.second.first, edge.first});
unite(edge.second.first, edge.second.second);
}
for (int i = 1; i <= n; ++i) {
if (heights[i] == 0) {
dfs(i, 0, 0);
}
}
for (int p = 1; p < 20; ++p) {
for (int i = 1; i <= n; ++i) {
neigh[p][i] = neigh[p - 1][neigh[p - 1][i]];
costs[p][i] = max(costs[p - 1][i], costs[p - 1][neigh[p - 1][i]]);
}
}
for (int i = 1; i <= k; ++i) {
int x, y;
cin >> x >> y;
cout << getMaxCost(x, y) << "\n";
}
return 0;
}