PAT甲级刷题之路——1129 Recommendation System

原题如下

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

题目大意

编写一个推荐系统判断用户的偏好。
输入:
列表的总数量N、可以给用户提供的最多推荐数K。
接下来是用户接触的列表。
输出:
输出前面最多的不超过k的数字,按出现次数排序,若出现次数相同则按照大小排列。

自己的想法

每知道一个数就重新排序一次,输出前不超过k个的推荐名单。
我的初步想法是先用map中的first和second分别对应数和出现次数,然后用vector来排序最后输出。(感觉会超时)
一开始想用set的,但是因为每次结构体里的次数会变,不知道怎么处理,所以没用

答案反馈

果然超时了T–T

错误1

1129
我还是老老实实用set吧,学习柳神代码:
柳神A1129传送门
哦哦,对于我之前用set的困惑,原来可以先删除原来的然后再插入新的鸭T–T

AC

在这里插入图片描述

总结

这一道题主要考察了对map的用法,我总结几点我自己不太熟的地方:

struct list {
	int data, index = 0;
	list(int a,int b):data(a),index(b){}
	bool operator <(const list &a) const{
		if (index != a.index) {
			return index > a.index;
		}
		else {
			return data < a.data;
		}
	}
};
  1. 一个是加载符号这一部分我不太熟,要多加训练
bool operator <(const list& a)const{
    if(index!=a.index){
        return index > a.index;
    }
    else{
        return data < a.data;
    }
}
  1. 还有一个是不从来没用的用法,可以省去很多麻烦:相当于在结构体中再加一个函数,这样可以方便map的insert使用。
list(int a, int b) data(a), index(b):{} 
  1. 还有一点就是map的用法,要想查询只能用迭代器来查询。

AC代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cctype>
#include<cstring>
#include<algorithm>
#include<ctime>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<set>
#include<queue>
#include<map>
#include<stack>
using namespace std;
const int maxn = 50010;
struct list {
	int data, index = 0;
	list(int a,int b):data(a),index(b){}
	bool operator <(const list &a) const{
		if (index != a.index) {
			return index > a.index;
		}
		else {
			return data < a.data;
		}
	}
};
set<list> user;
int number[maxn] = { 0 };
int main() {
#ifdef test
	 freopen("input.txt", "r", stdin);
#endif
	int n, k;
	cin >> n >> k;
	for (int i = 0; i < n; i++) {
		int t;
		cin >>t;
		if (i != 0) {
			cout << t << ':';
			int cnt = 0;
			for (auto it = user.begin(); it != user.end() && cnt < k; it++,cnt++) {
				cout << ' ' << it->data;
			}
			cout << endl;
		}
		auto it = user.find(list(t, number[t]));
		if (it!=user.end()) {
			user.erase(it);
		}
		number[t]++;
		user.insert(list(t, number[t]));
	}
	return 0;
}

结语

希望这段时间能挺过去吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值