PAT1129 Recommendation System(set,运算符重载)

原题

在这里插入图片描述

题目大意及思路

  • **题目大意:**每输入一个数,就输出k个推荐的数(首先按之前出现频率最高的从后排,若出现频率一致,则index小的在前)
  • **分析:**这个推荐是实时更新的,所以选取一个合适的数据结构很重要,这里我选取了数据类型为node的set结构,在这里由于需要排序,所以重载了运算符。

代码

#include<iostream>
#include<vector>
#include<set>
using namespace std;
struct node{
	int index,frequency;
	bool operator < (const node &a) const{
		return frequency==a.frequency?index<a.index:frequency>a.frequency; 
	}
};
int main(){
	int n,k;
	cin>>n>>k;
	vector<int> fre(n+1);
	set<node> s;
	for(int i=0;i<n;i++){
		int index;
		cin>>index;
		int j=0;
		if(s.size()!=0) printf("%d: ",index);
		for(auto it=s.begin();it!=s.end()&&j<k;it++){
			printf("%d",it->index);
			if(j==k-1||j==s.size()-1) printf("\n");
			else printf(" ");
			j++;
		}
		if(fre[index]!=0) s.erase({index,fre[index]});
		s.insert({index,++fre[index]});
	}
	return 0;
}

运行截图

在这里插入图片描述

收获

  • 重载运算符基本格式:
bool operator < (const node &a) const{
		return frequency==a.frequency?index<a.index:frequency>a.frequency; 
	}
  • 用迭代器的一般这样取值:it->index
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值