1129 Recommendation System

 

#include<bits/stdc++.h> 
using namespace std;
int book[50001];
struct Node{
	int data;
	int tms;
	bool operator < (const Node &a) const{
		if(a.tms!=this->tms) return this->tms>a.tms;
		else return this->data<a.data;
	}
};
int main()
{
	freopen("in.txt","r",stdin);
	int n,k;cin>>n>>k;
	set<Node> s;
	for(int i=0;i<n;i++){
		int p;cin>>p;
		if(i!=0){
			cout<<p<<":";
			int cnt=0;
			for(auto it=s.begin();it!=s.end()&&cnt<k;it++){
				printf(" %d",(*it).data);cnt++;
			}
			cout<<endl;
		}
		auto it=s.find(Node{p,book[p]});
		if(it!=s.end()) s.erase(it);
		book[p]++;
		s.insert(Node{p,book[p]});
	}
	return 0;
}

 下面是以前写的代码。。。用来vector排序没用运算符重载的话最后三个测试点会超时,除了重载目前我还没看到其他解法。。。

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct Node{
	int key;
	int cnt;
};
bool cmp(Node a,Node b){
	if(a.cnt!=b.cnt) return a.cnt>b.cnt;
	else if(a.key!=b.key) return a.key<b.key;
}
int main()
{
	#ifdef ONLINE_JUDGE
	#else
	freopen("in.txt","r",stdin);
	#endif
	int n,k;
	cin>>n>>k;
	int hash[50001]={};
	vector<Node> node;
	for(int i=0;i<n;i++){
		int temp1;
		cin>>temp1;
		hash[temp1]++;
		Node temp2;
		temp2.cnt=hash[temp1];
		temp2.key=temp1;
		if(i>0){
			cout<<temp1<<":";	
			for(int j=0;j<node.size()&&j<k;j++){
				cout<<' '<<node[j].key;
			}
			cout<<endl;
		}
		int sign=0;
		vector<Node>::iterator it;
		for(it=node.begin();it!=node.end();it++){
			if((*it).key==temp1){
				sign=1;break;
			}
		}
		if(sign==1){
			node.erase(it);
			node.push_back(temp2);
		}else{
			node.push_back(temp2);
		}
		sort(node.begin(),node.end(),cmp);
	}
	node.clear();
	return 0;
}

得到18分,两个点运行超时,大概是因为第二层循环找重复的key值那一步,可以考虑用set的find函数?

#include<bits/stdc++.h>
using namespace std;
struct Node{
	int data;
	int tms;
};
bool cmp(Node a,Node b){
	if(a.tms!=b.tms) return a.tms>b.tms;
	else return a.data<b.data;
}
int main()
{
	freopen("in.txt","r",stdin);
	int n,k;cin>>n>>k;
	vector<int> temp;
	vector<Node> t1,t2;t1.resize(n+1);
	for(int i=0;i<n;i++){
		int p;cin>>p;
		t1[p].data=p;
		t1[p].tms++;
		if(temp.size()!=0){
			cout<<p<<": ";
			for(int j=0;j<temp.size();j++){
				if(j==0) cout<<temp[j];
				else cout<<' '<<temp[j];
			}
			cout<<endl;
			temp.clear();
		}
		t2=t1;
		sort(t2.begin(),t2.end(),cmp);
		int cnt=0;
		for(int j=0;j<t2.size();j++){
			if(t2[j].tms!=0&&cnt<k){
				temp.push_back(t2[j].data);cnt++;
			}
		}
		t2.clear();
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值