L2-039 清点代码库(容器的妙用)

天梯赛L2-039

先给出代码,最后进行讲解

✅️✅️✅️

#include <iostream>
#include <vector>
#include <algorithm>
#include <map> // 注意:unordered_map 默认不支持 vector 作 Key,改用 map 更方便

using namespace std;

// 使用 vector<int> 作为键,自动处理数字大小比较
map<vector<int>, int> cnt;

bool cmpl(const pair<vector<int>, int> &a, const pair<vector<int>, int> &b)
{
    if (a.second != b.second)
    {
        return a.second > b.second; // 次数降序
    }
    return a.first < b.first; // 向量(数字序列)升序
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n, m;
    cin >> n >> m;

    for (int i = 0; i < n; i++)
    {
        vector<int> row(m);
        for (int j = 0; j < m; j++)
        {
            cin >> row[j];
        }
        cnt[row]++;
    }

    vector<pair<vector<int>, int>> res(cnt.begin(), cnt.end());
    sort(res.begin(), res.end(), cmpl);

    cout << res.size() << endl;
    for (int i = 0; i < res.size(); i++)
    {
        cout << res[i].second;
        for (int j = 0; j < m; j++)
        {
            cout <<" "<< res[i].first[j]; 
        }
        cout << endl;
    }

    return 0;
}

讲解

题目要我们求出不同代码库的数量,还要按一定顺序输出。我们这里利用键值对,让不同的代码输出与其数量匹配,非常直接,key就是我们输入的,这里我们采用的是用vector 来存输入的几个数据,有人会想:“我用字符串作为键值不也可以吗?” ,作为计数器,确实可以,但是这不方便我们后续进行排序,我们的期望是直接根据输入的“串”进行排序(最简单)但是如果是字符串的话,进行排序时会变得麻烦,因为它是按一个字符一个字符地去比较,在数学中,10比2大
但是在字符串中,10比2小,所以用字符串不利于后续的排序(当然也有解决方法)。

但是map本身并不支持排序,所以需要把map的结果存到一个vector数组里,而map本身就是一个pair,所以用pair的形式创建一个res,并把cnt放进去(这里的语法之前确实没见过),我们再写一个比较函数,定义比较规则。

posted @ 2026-03-17 14:24  shuiwangrenjia  阅读(2)  评论(0)    收藏  举报