PAT A1129 Recommendation System (25 分)

Recommendation system predicts the preference that a user would give to an item. Now you are asked to program a very simple recommendation system that rates the user's preference by the number of times that an item has been accessed by this user.

Input Specification:

Each input file contains one test case. For each test case, the first line contains two positive integers: N (≤ 50,000), the total number of queries, and K (≤ 10), the maximum number of recommendations the system must show to the user. Then given in the second line are the indices of items that the user is accessing -- for the sake of simplicity, all the items are indexed from 1 to N. All the numbers in a line are separated by a space.

Output Specification:

For each case, process the queries one by one. Output the recommendations for each query in a line in the format:

query: rec[1] rec[2] ... rec[K]

where query is the item that the user is accessing, and rec[i] (i=1, ... K) is the i-th item that the system recommends to the user. The first K items that have been accessed most frequently are supposed to be recommended in non-increasing order of their frequencies. If there is a tie, the items will be ordered by their indices in increasing order.

Note: there is no output for the first item since it is impossible to give any recommendation at the time. It is guaranteed to have the output for at least one query.

Sample Input:

12 3
3 5 7 5 5 3 2 1 8 3 8 12

Sample Output:

5: 3
7: 3 5
5: 3 5 7
5: 5 3 7
3: 5 3 7
2: 5 3 7
1: 5 3 2
8: 5 3 1
3: 5 3 1
8: 3 5 1
12: 3 5 8

思路:
题目要求在每一个元素时候将之前各个元素按照出现的次数进行降序排列,并且输出指定个数的前几个元素,因为涉及到重复元素所以首先应该选择set容器来存储数据,用一个结构体来保存元素值和其对应出现的次数,并且对set容器排序的方法进行重载,重载方式看以下结构体中的代码形式即可,需要注意的一点是,在每一次新的元素加入前,例如元素5加入前,先要查询set容器中是否已经存在5号元素了,如果已经存在则需要将其出现的次数+1,也就是将原先的这个结构体结点删除重新加入一个5号元素,并且出现次数+1,这可以用set容器的find方法来实现。

代码实现:

#include <iostream>
#include <set>
#include <vector>
using namespace std;
const int N=50010;
struct node {
	int data,cnt;
	bool friend operator < (node x,node y) {//set运算符重载
		if(x.cnt!=y.cnt) return x.cnt>y.cnt;
		else return x.data<y.data;
	}
} Node[N];
int hashT[N]= {0};

int main() {
	for(int i=0; i<N; i++) {
		Node[i].data=i;
		Node[i].cnt=0;
	}
	int n,k,val;
	cin>>n>>k;
	vector<int> sq;
	while(n--) {
		scanf("%d",&val);
		sq.push_back(val);
	}
	set<node> st;
	Node[sq[0]].cnt++;
	hashT[sq[0]]++;
	st.insert(Node[sq[0]]);
	for(int i=1; i<sq.size(); i++) {
		int size=st.size();
		if(size>k) size=k;
		printf("%d:",sq[i]);
		set<node>::iterator it=st.begin();
		while(size--) {
			printf(" %d",*it);
			it++;
		}
		st.erase(node {sq[i],hashT[sq[i]]});
		hashT[sq[i]]++;
		st.insert(node {sq[i],hashT[sq[i]]});
		printf("\n");
	}
	return 0;
}
```1129 Recommendation System (25 分)
posted @ 2021-02-02 19:34  coderJ_ONE  阅读(78)  评论(0)    收藏  举报