1129 Recommendation System(25分)

题目翻译:

写一个推荐系统,用户点击一个数字后,推荐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++;
	}
}

坑点:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值