-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
45 lines (44 loc) · 1.4 KB
/
Solution.java
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
40
41
42
43
44
45
class Solution {
public int[] countPairs(int n, int[][] edges, int[] queries) {
int[] cnt = new int[n];
Map<Integer, Integer> g = new HashMap<>();
for (var e : edges) {
int a = e[0] - 1, b = e[1] - 1;
++cnt[a];
++cnt[b];
int k = Math.min(a, b) * n + Math.max(a, b);
g.merge(k, 1, Integer::sum);
}
int[] s = cnt.clone();
Arrays.sort(s);
int[] ans = new int[queries.length];
for (int i = 0; i < queries.length; ++i) {
int t = queries[i];
for (int j = 0; j < n; ++j) {
int x = s[j];
int k = search(s, t - x, j + 1);
ans[i] += n - k;
}
for (var e : g.entrySet()) {
int a = e.getKey() / n, b = e.getKey() % n;
int v = e.getValue();
if (cnt[a] + cnt[b] > t && cnt[a] + cnt[b] - v <= t) {
--ans[i];
}
}
}
return ans;
}
private int search(int[] arr, int x, int i) {
int left = i, right = arr.length;
while (left < right) {
int mid = (left + right) >> 1;
if (arr[mid] > x) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}