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
- 46 lines of C++ from the credited upstream file 1782.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 5 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:3 vector<int> countPairs(int n, vector<vector<int>>& edges,4 vector<int>& queries) {5 vector<int> ans(queries.size());6 7 8 vector<int> count(n + 1);9 10 11 vector<unordered_map<int, int>> shared(n + 1);12 13 for (const vector<int>& edge : edges) {14 const int u = edge[0];15 const int v = edge[1];16 ++count[u];17 ++count[v];18 ++shared[min(u, v)][max(u, v)];19 }20 21 vector<int> sortedCount(count);22 ranges::sort(sortedCount);23 24 int k = 0;25 for (const int query : queries) {26 for (int i = 1, j = n; i < j;)27 if (sortedCount[i] + sortedCount[j] > query)28 29 30 31 32 33 ans[k] += (j--) - i;34 else35 ++i;36 for (int i = 1; i <= n; ++i)37 for (const auto& [j, sh] : shared[i])38 if (count[i] + count[j] > query && count[i] + count[j] - sh <= query)39 --ans[k];40 ++k;41 }42 43 return ans;44 }45};46