题目翻译:
写一个推荐系统,用户点击一个数字后,推荐k个数字,对应于此前点击最频繁的数字,如果两个数字频率相同,则输出较小的。
题解思路:
设置一个数据结构node,重载比较符号。用一个set<node>
完成排序,每次循环输出前k个(若有)。为了O(1)时间找到此前出现次数,单独设置一个数组记录。每次更新数据后,删除原node,插入新node。
代码:
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 50001;
int n, k, cntn[N];
struct node {
int cnt, val;//频率,下标
node(int a, int b) : cnt(a), val(b) {};
bool operator <(const node A) const {
return cnt != A.cnt ? cnt > A.cnt : val < A.val;
}
};
set<node> rec;
vector<int> a(N);
int main() {
cin >> n >> k >> a[0];
cntn[a[0]]++, rec.insert({ 1, a[0] });
for (int i = 1; i < n; i++) {
cin >> a[i];
cout << a[i] << ":";
int c = 0;
for (auto j = rec.begin(); c != k && j != rec.end(); j++, c++)
cout << " " << j->val;
cout << endl;
rec.erase({ cntn[a[i]], a[i] });
cntn[a[i]]++;
rec.insert({ cntn[a[i]], a[i] });
}
return 0;
}
暴力求解(只能通过前两个测试点):
每次更新后再次排序时间开销太大了
#include<bits/stdc++.h>
using namespace std;
int N, t_max;
vector<pair<int,int>> v(50010), t(50010);//下标-频率
bool comp(pair<int, int> a, pair<int, int> b)
{
if (a.second != b.second)
return a.second > b.second;
else
return a.first < b.first;
}
int main()
{
cin >> N >> t_max;
for (int i = 0;i <= N;i++)
v[i].first = i;
for (int i = 0;i < N;i++)
{
int p;cin >> p;
if (i != 0)
{
t = v;
sort(t.begin(), t.begin() + N, comp);
cout << p << ":";
for (int j = 0;j < t_max;j++)
{
if (t[j].second)
cout << " " << t[j].first;
}
cout << endl;
}
v[p].second++;
}
}
坑点:
无