[C++] Using stack and math formula (easy-understanding)
\nclass Solution {\npublic:\n    long long countExcellentPairs(vector<int>& a, int k) {\n        int n = a.size();\n        vector<long long> cnt;\n        set<
```\nclass Solution {\npublic:\n    long long countExcellentPairs(vector<int>& a, int k) {\n        int n = a.size();\n        vector<long long> cnt;\n        set<int> s;\n        for(int i = 0; i < n; i++) s.insert(a[i]);\n        for(auto i = s.begin(); i != s.end(); i++) {\n            cnt.push_back(__builtin_popcount(*i));\n        }\n        sort(cnt.begin(), cnt.end(), greater<int>());\n        stack<int> st;\n        long long ans = 0;\n        for(int i = 0; i < cnt.size(); i++) {\n            while(!st.empty() && cnt[st.top()] + cnt[i] < k) st.pop();\n            if(!st.empty()) ans += (1 + st.top()) * 2LL;\n            if(2 * cnt[i] >= k) ans++;\n            st.push(i);\n        }\n        return ans;\n    }\n};\n```
['Sorting']