Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- #include <ext/pb_ds/assoc_container.hpp>
- #include <ext/pb_ds/tree_policy.hpp>
- using namespace std;
- using namespace __gnu_pbds;
- #define debug(x) cerr << '[' << (#x) << "] = " << x << '\n';
- template<class T> using ordered_set = tree<T, null_type , less<T> , rb_tree_tag , tree_order_statistics_node_update> ;
- const int maxn = 2e4 + 4;
- int sz[maxn], parent[maxn];
- void PlayGround(int N) {
- int M, S;
- cin >> M >> S;
- for(int i=1; i<=N; ++i) {
- sz[i] = 1, parent[i] = i;
- }
- vector<vector<pair<int,int>>>MST(N+1, vector<pair<int,int>>());
- vector<pair<int,pair<int,int>>>Edges(M);
- for(auto& it : Edges) {
- cin >> it.second.first >> it.second.second >> it.first;
- }
- function<int(int)> find_set = [&] (int v) {
- if(parent[v]==v)
- return v;
- return parent[v] = find_set(parent[v]);
- };
- auto Unite = [&] (int u, int v) {
- u = find_set(u);
- v = find_set(v);
- if(sz[u]<sz[v]) swap(u, v);
- sz[u] += sz[v];
- parent[v] = u;
- };
- sort(Edges.rbegin(), Edges.rend());
- for(auto it : Edges) {
- int u = it.second.first, v = it.second.second, w = it.first;
- if(find_set(u)!=find_set(v)) {
- Unite(u, v);
- MST[u].push_back(make_pair(v, w));
- MST[v].push_back(make_pair(u, w));
- }
- }
- int l = 20, timer = 0;
- vector<vector<int>>up(N+1, vector<int>(l+1)), mn(N+1, vector<int>(l+1));
- vector<int>tin(N+1), tout(N+1);
- function<void(int,int,int)> DFS = [&] (int node, int parent, int toParent) {
- tin[node] = timer++;
- up[node][0] = parent;
- mn[node][0] = toParent;
- for(int i=1; i<=l; ++i) {
- up[node][i] = up[up[node][i-1]][i-1];
- mn[node][i] = min(mn[up[node][i-1]][i-1], mn[node][i-1]);
- }
- for(auto it : MST[node]) if(it.first!=parent) {
- DFS(it.first, node, it.second);
- }
- tout[node] = timer++;
- };
- DFS(1, 1, INT_MAX);
- auto isAncestor = [=] (int u, int v) {
- return tin[u] <= tin[v] && tout[u] >= tout[v];
- };
- auto ClimbToLCA = [=] (int u, int v, int& answer) {
- for(int i=l; i>=0; --i) if(!isAncestor(up[u][i], v)) {
- answer = min(answer, mn[u][i]);
- u = up[u][i];
- }
- if(!isAncestor(u, v)) {
- answer = min(answer, mn[u][0]);
- }
- };
- while(S--) {
- int u, v; cin >> u >> v;
- int answer = INT_MAX;
- ClimbToLCA(u, v, answer);
- ClimbToLCA(v, u, answer);
- cout << answer << '\n';
- }
- #ifndef ONLINE_JUDGE
- cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
- #endif
- }
- int main() {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- #ifndef ONLINE_JUDGE
- freopen("input.txt", "r", stdin);
- #endif
- int N;
- while(cin >> N) {
- PlayGround(N);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement