原题如下
题目大意
编写一个推荐系统判断用户的偏好。
输入:
列表的总数量N、可以给用户提供的最多推荐数K。
接下来是用户接触的列表。
输出:
输出前面最多的不超过k的数字,按出现次数排序,若出现次数相同则按照大小排列。
自己的想法
每知道一个数就重新排序一次,输出前不超过k个的推荐名单。
我的初步想法是先用map中的first和second分别对应数和出现次数,然后用vector来排序最后输出。(感觉会超时)
一开始想用set的,但是因为每次结构体里的次数会变,不知道怎么处理,所以没用
答案反馈
果然超时了T–T
错误1
我还是老老实实用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;
}
}
};
- 一个是加载符号这一部分我不太熟,要多加训练
bool operator <(const list& a)const{
if(index!=a.index){
return index > a.index;
}
else{
return data < a.data;
}
}
- 还有一个是不从来没用的用法,可以省去很多麻烦:相当于在结构体中再加一个函数,这样可以方便map的insert使用。
list(int a, int b) data(a), index(b):{}
- 还有一点就是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;
}
结语
希望这段时间能挺过去吧