http://www.cnblogs.com/pangxiaodong/archive/2011/09/24/2189593.html
问题描述:我这里有很多学生的学号(有重复的),已知其中有K个学生,他们的学号出现的次数都超过了总数的1/(K+1),请把这K个学号找出来。
上代码:
#include<iostream>
#include<list>
#include<utility>
using namespace std;
template<typename T,size_t N>
inline size_t getArrLen(T (&arr)[N]){
return N;
}
const int K=3;
int main(){
string IDs[]={"M201070347","M201070360","M201070359","M201070351","M201070358","M201070358","M201070359","M201070360","M201070360","M201070358","M201070359"};
int len=getArrLen(IDs);
list<pair<string,int> > words;
for(int i=0;i<len;i++){
list<pair<string,int> >::iterator pos=words.begin();
while(pos!=words.end()){
if(pos->first==IDs[i])
break;
pos++;
}
if(pos!=words.end()){ //在words中
pos->second++;
}else{ //不在words中
if(words.size()<K){ //words中元素还不够K个
words.push_back(pair<string,int>(IDs[i],1));
}
else{ //words中元素已够K个
list<pair<string,int> >::iterator itr=words.begin();
while(itr!=words.end()){
itr->second--;
itr++;
}
itr=words.begin();
while(itr!=words.end()){
if(itr->second==0){
list<pair<string,int> >::iterator itt=itr;
itr++;
words.erase(itt);
}else{
itr++;
}
}
}
}
}
list<pair<string,int> >::iterator itr=words.begin();
while(itr!=words.end()){
cout<<itr->first<<"\t";
itr++;
}
cout<<endl;
return 0;
}