Approach
Sorting and greedy selection
For Count Pairs Of Nodes, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 50 lines of Java from the credited upstream file 1782.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 6 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] countPairs(int n, int[][] edges, int[] queries) {3 int[] ans = new int[queries.length];4 5 6 int[] count = new int[n + 1];7 8 9 Map<Integer, Integer>[] shared = new Map[n + 1];10 11 for (int i = 1; i <= n; ++i)12 shared[i] = new HashMap<>();13 14 for (int[] edge : edges) {15 final int u = edge[0];16 final int v = edge[1];17 ++count[u];18 ++count[v];19 shared[Math.min(u, v)].merge(Math.max(u, v), 1, Integer::sum);20 }21 22 int[] sortedCount = count.clone();23 Arrays.sort(sortedCount);24 25 int k = 0;26 for (final int query : queries) {27 for (int i = 1, j = n; i < j;)28 if (sortedCount[i] + sortedCount[j] > query)29 30 31 32 33 34 ans[k] += (j--) - i;35 else36 ++i;37 for (int i = 1; i <= n; ++i)38 for (Map.Entry<Integer, Integer> p : shared[i].entrySet()) {39 final int j = p.getKey();40 final int sh = p.getValue();41 if (count[i] + count[j] > query && count[i] + count[j] - sh <= query)42 --ans[k];43 }44 ++k;45 }46 47 return ans;48 }49}50