甲级1129.
大意:给你一个网页上的货物编号,客户每次点击一次,要输入之前他访问过的最多的K个商品。
难点:一开始想着用双map搞半天没搞出来。后来看了题解发现一个重载和set的配合使用就可以简单的解决这题。
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <unordered_map>
#include <map>
#include <math.h>
#include <string>
#include <stack>
#include <numeric>
#include <set>
#include <list>
using namespace std;
int n, k;
const int maxnum = 50005;
struct Access
{
int ID, times;
bool operator < (const Access &a) const //set默认按升序排列,即小的在前面 括号内的是比较对象,这里是this和a对比
{
if (times != a.times)
return this->times > a.times; //这里重载等于说搞成了大于号,出现次数大的在前面
else
return this->ID < a.ID;
}
};
int book[maxnum]; //商品ID和出现次数的数组记录,用来更新set用的
int main()
{
cin >> n >> k;
set<Access> S;
for (int i = 0; i < n; i++)
{
int tmp;
cin >> tmp;
if (i != 0)
{
cout << tmp << ":";
int cnt = 0;
for (auto it = S.begin();cnt < k && it != S.end(); it++)
{
cout << " " << it->ID;
cnt++;
}
cout << "\n";
} //以上部分为输出
auto it = S.find(Access{ tmp,book[tmp] }); //find内部是结构体格式
if (it != S.end())//已有重复
S.erase(it); //删除掉旧节点
book[tmp]++;
S.insert(Access{ tmp,book[tmp] });
}
return 0;
}