Skip to content

Commit

Permalink
graph
Browse files Browse the repository at this point in the history
  • Loading branch information
keineahnung2345 authored Oct 21, 2020
1 parent f5bb1e1 commit 9348bc9
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions 1627. Graph Connectivity With Threshold.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//graph
//WA
//57 / 66 test cases passed.
//indirectly connection also considered true?
Expand Down Expand Up @@ -41,6 +42,75 @@ class Solution {
}
};

//graph
//fix above: indirectly connected cities should also be seen as connected
//TLE
//64 / 66 test cases passed.
class Solution {
public:
int gcd(int x, int y){
if(y == 0) return x;
return gcd(y, x%y);
}

int encode(int& i, int& j, int& n){
return i*(n+1)+j;
}

vector<bool> areConnected(int n, int threshold, vector<vector<int>>& queries) {
int m = queries.size();
vector<bool> ans(m, true);

if(threshold == 0){
return ans;
}

vector<unordered_set<int>> adjList(n+1);

for(int i = 1; i <= n; ++i){
for(int j = i+1; j <= n; ++j){
if(gcd(i, j) > threshold){
adjList[i].insert(j);
adjList[j].insert(i);
}
}
}

for(int i = 0; i < m; ++i){
vector<int>& query = queries[i];
if(query[0] > query[1]) swap(query[0], query[1]);

bool connected = false;

queue<int> q;
vector<bool> visited(n+1, false);
int cur;

q.push(query[0]);
visited[query[0]] = true;

while(!q.empty()){
cur = q.front(); q.pop();

if(cur == query[1]){
connected = true;
break;
}

for(const int& nei : adjList[cur]){
if(visited[nei]) continue;
visited[nei] = true;
q.push(nei);
}
}

ans[i] = connected;
}

return ans;
}
};

//DSU
//from hint
//Runtime: 360 ms, faster than 57.32% of C++ online submissions for Graph Connectivity With Threshold.
Expand Down

0 comments on commit 9348bc9

Please sign in to comment.