1 条题解

  • 0
    @ 2026-3-24 16:09:09

    map转vector 自定义排序

    #include <bits/stdc++.h>
    using namespace std;
    #define int long long 
    typedef pair<int, int> p;
    int n;
    map<int, int> cnt;
    // 自定义排序规则:次数降序,次数相同值升序
    bool cmp(p a, p b) {//first对应值 ,second对应它出现的次数
        if (a.second == b.second) return a.first < b.first;//出现次数相等 值小的在前面
        return a.second > b.second;//出现次数多的在前面
    }
    
    signed main() {
        cin >> n;
        while (n--) {
            int x;
            cin >> x;
            cnt[x]++;//计数 由于map是按值的大小排序 我们需要转换成vector 这样可以自定义排序
        }
        vector<p> vec;//first对应值 ,second对应它出现的次数
        // 存入vector
        for (auto &it : cnt) {
            vec.push_back(it);
        }
        // 自定义排序
        sort(vec.begin(), vec.end(), cmp);
        for (auto &q : vec) {
            cout << q.first << " " << q.second << endl;
        }
        return 0;
    }