foj 1664 Top K different numbers
Problem Description
There are N numbers in an array. Now your question is to select the top K different numbers in the array. The top K different numbers are the largest K different numbers in the array. If there are less than K different numbers, just output “-1” instead.
Input
There are multiply test cases. For each test case, the first line are two integer N and K(1≤N≤10000, 1≤K≤N). In the second line, there are N integers which are separated by a space. It is guaranteed that the element in the array will fit within a 32-bit integer.
Output
For each test case, output the top K different numbers increasingly. Please separate the K numbers by a space. If there are less than K different numbers, just output “-1” instead.
Sample Input
2 1
1 2
3 2
1 1 2
3 3
1 1 2
Sample Output
2
1 2
-1
这题方法很多种,我是使用了set的方法。
方法在代码中体现
#include<iostream>
#include<set>//定义
#include<cstdlib>
#include<cstring>
using namespace std;
int a[10001];
int MyCompare(const void *e1,const void *e2){//快排,从小到大(*p1-*p2)
int *p1,*p2;
p1=(int *)e1;
p2=(int *)e2;
return *p1-*p2;
}
int main()
{
int n,i,k,num;
set<int>p;
set<int>::iterator it; //迭代器,类似于指针,自我理解,来获得地址
while(cin>>n){
cin>>k;
memset(a,0,sizeof(a));//清空初始化,用到cstring头文件
p.clear();
for(i=0;i<n;i++)
{
cin>>num;
p.insert(num);//存到set中,重复的会过滤
}
if(k>p.size()){//不重复的个数p.size();函数
cout<<"-1";
}
else{
for(it=p.begin(),i=0;it!=p.end();i++,it++)//起始地址p.begin();末尾p.end();
{
a[i]=*it;//赋值到数组中
}
qsort(a,len,sizeof(int),MyCompare);//快排
for(i=p.size()-k;i<p.size();i++)
{
cout<< a[i];
if(i!=p.size()-1) cout<<" ";
}
}
cout<<endl;
}
return 0;
}
浙公网安备 33010602011771号