Submission

Status:

(PPPPPPPPP)(PPPP)(PPPPPP)(PPPPPPPPPP)

Subtask/Task Score:

{25/25}{25/25}{20/20}{30/30}

Score: 100

User: Nathako9n

Problemset: เดินทางข้ามชุมชน

Language: cpp

Time: 0.151 second

Submitted On: 2026-01-24 11:03:09

#include <bits/stdc++.h>
#define endl '\n'
using namespace std;

const int N = 1e5+5;
// Use int instead of long long to save memory (32MB limit is tight)
int n, m, q;
int head[N+2];
int sz[N+2]; // Array to keep track of component size for optimization

// Using structs can be slightly more memory efficient/readable than tuples
struct Edge {
    int w, u, v;
    // Overload < operator for sorting
    bool operator<(const Edge& other) const {
        return w < other.w;
    }
};

struct Query {
    int w, u, v, id;
    bool operator<(const Query& other) const {
        return w < other.w;
    }
};

vector<Edge> ed;
vector<Query> que;
bool ans[300005];

int fh(int i){
    if(i == head[i]) return i;
    return head[i] = fh(head[i]); // Path Compression
}

// Optimized Union function (Union by Size)
void uh(int u, int v){
    u = fh(u);
    v = fh(v);
    if(u == v) return;

    // Always attach the smaller tree to the larger tree
    if(sz[u] < sz[v]) swap(u, v);
    head[v] = u; // u is now the parent of v
    sz[u] += sz[v]; // update size of the new root
}

int main(){
    // Optimize I/O operations
    ios::sync_with_stdio(0);
    cin.tie(0);

    if (!(cin >> n >> m >> q)) return 0;

    // Initialize DSU
    for(int i = 1; i <= n; i++) {
        head[i] = i;
        sz[i] = 1; // Initial size of every component is 1
    }

    for(int i = 1; i <= m; i++){
        int u, v, w;
        cin >> u >> v >> w;
        u++; v++; // 0-based to 1-based index
        ed.push_back({w, u, v});
    }

    // Sort edges by weight ascending
    sort(ed.begin(), ed.end());

    for(int i = 1; i <= q; i++){
        int u, v, w;
        cin >> u >> v >> w;
        u++; v++;
        que.push_back({w, u, v, i});
    }

    // Sort queries by capacity ascending
    sort(que.begin(), que.end());

    int edge_idx = 0;

    // Process queries
    for(const auto& qry : que){
        // While edges are smaller than or equal to current query capacity, add them
        while(edge_idx < m && ed[edge_idx].w <= qry.w){
            uh(ed[edge_idx].u, ed[edge_idx].v);
            edge_idx++;
        }

        // Check if start and end nodes are in the same component
        ans[qry.id] = (fh(qry.u) == fh(qry.v));
    }

    for(int i = 1; i <= q; i++){
        if(ans[i]) cout << "Yes" << endl;
        else cout << "No" << endl;
    }

    return 0;
}