Posted on

Description

Submission

class DistanceLimitedPathsExist {
    map<int, vector<int>> Map;
    vector<int> v;

    int Find(int n, vector<int>& v) {
        while(v[n] != n) {
            v[n] = v[v[n]];
            n = v[n];
        }
        return n;
    }
public:
    DistanceLimitedPathsExist(int n, vector<vector<int>>& edgeList) {
        v.resize(n);
        for(int i = 0; i < n; ++i) {
            v[i] = i;
        }
        sort(edgeList.begin(), edgeList.end(), [](auto& e1, auto&e2) {
            return e1[2] < e2[2];
        });
        for(auto edge: edgeList) {
            v[Find(edge[0], v)] = Find(edge[1], v);
            Map[edge[2]] = vector<int>(v.cbegin(), v.cend());
        }
    }
    
    bool query(int p, int q, int limit) {
        auto iter = Map.lower_bound(limit);
        if(iter == Map.end() || iter == Map.begin()) return false;
        iter = prev(iter);
        return Find(p, iter->second) == Find(q, iter->second);
    }
};

/**
 * Your DistanceLimitedPathsExist object will be instantiated and called as such:
 * DistanceLimitedPathsExist* obj = new DistanceLimitedPathsExist(n, edgeList);
 * bool param_1 = obj->query(p,q,limit);
 */

Leave a Reply

Your email address will not be published. Required fields are marked *