[LeetCode] Count Pairs Of Nodes

1782. Count Pairs Of Nodes

You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.

Let incident(a, b) be defined as the number of edges that are connected to either node a or b.

The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:

  • a < b
  • incident(a, b) > queries[j]

Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.

Note that there can be multiple edges between the same two nodes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
vector<int> countPairs(int n, vector<vector<int>>& edges, vector<int>& queries) {
vector<int> c(n + 1), sc, res;
vector<unordered_map<int, int>> common(n + 1);
for(auto& e : edges) {
c[e[0]]++;
c[e[1]]++;
common[min(e[0],e[1])][max(e[0],e[1])]++;
}
sc = c;
sort(begin(sc), end(sc));
unordered_map<int, int> cache;
for(auto& q : queries) {
if(!cache.count(q)) {
int sum = 0;

for(int i = 1, j = n; i < j;) {
if(q < sc[i] + sc[j]) {
sum += j - i;
j--;
} else i++;
}

for(int i = 1; i <= n; i++) {
for(auto [j, com] : common[i]) {
if(q < c[i] + c[j] and q >= c[i] + c[j] - com)
sum--;
}
}

cache[q] = sum;
}
res.push_back(cache[q]);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/24/PS/LeetCode/count-pairs-of-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.