代码1:
#include<set>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int,int>pii;
const int N=1e5+10;
int st[N];
int n,k;
int con[N];
vector<int>res;
bool cmp(int a,int b){
if(con[a]!=con[b]){
return con[a]>con[b];
}
else
return a<b;
}
int main(){
cin>>n>>k;
for(int i=0;i<n;i++){
int x;
cin>>x;
if(i){
printf("%d:",x);
for(int j=0;j<res.size()&&j<k;j++){
printf(" %d",res[j]);
}
cout<<endl;
}
if(!st[x]){
st[x]=1;
if(res.size()>k){
st[res[k]]=0;
res[k]=x;
}
else{
res.push_back(x);
}
}
con[x]++;
sort(res.begin(),res.end(),cmp);
}
return 0;
}
代码2:
#include<set>
#include<iostream>
using namespace std;
typedef pair<int,int>pii;
const int N=1e5+10;
int st[N];
int n,k;
set<pii>res;
int main(){
cin>>n>>k;
for(int i=0;i<n;i++){
int x;
cin>>x;
if(i){
printf("%d:",x);
int p=0;
for(auto &t:res){
printf(" %d",t.second);
p++;
if(p>=k)
break;
}
cout<<endl;
}
if(!st[x]){
st[x]=1;
res.insert({-1,x});
}
else{
res.erase({-st[x],x});
st[x]+=1;
res.insert({-st[x],x});
}
}
return 0;
}