【PTA刷题】甲级 重载运算符

甲级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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值