#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;
}