sort
Time Limit : 6000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 15 Accepted Submission(s) : 9
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
给你n个整数,请按从大到小的顺序输出其中前m大的数。
Input
每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。
Output
对每组测试数据按从大到小的顺序输出前m大的数。
Sample Input
5 3 3 -35 92 213 -644
Sample Output
213 92 3
一道简单的排序题,但由于数据量比较大所以快排有点吃力AC时间 937MS,冒泡估计是肯定不行了,快排的代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<time.h>
int data[1000000];
int N,M;
int cmp(const void *a,const void *b)
{
return *(int *)b-*(int *)a;
}
int main()
{
while(~scanf("%d%d",&N,&M))
{
for(int i=0;i<N;++i)
scanf("%d",&data[i]);
qsort(data,N,sizeof(int),cmp);
for(int i=0;i<M;++i)
{
printf("%d",data[i]);
if(i<M-1)
printf(" ");
}
puts("");
}
return 0;
}
接下来是优先队列,有一段时间没写了,够呛。AC时间750MS,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <conio.h>
int queue[1000005], CN;
int M,N;
void swap( int x, int y )
{
int t= queue[x];
queue[x]= queue[y];
queue[y]= t;
}
void up( int x )
{
if( x> 1 )
{
if( queue[x]> queue[x/ 2] )
{
swap( x, x/ 2 );
up( x/ 2 );
}
}
}
void down( int x )
{// 将小的元素沉到下面去
int p= 2* x;
if( p<= CN )
{
if( p+ 1<= CN&& queue[p]< queue[p+ 1] )
{
++p;
}
if( queue[x]< queue[p] )
{
swap( x, p );
down( p );
}
}
}
void pop( )
{
queue[1]= queue[CN--];
down( 1 );
}
void insert( int x )
{
queue[++CN]= x;
up( CN );
}
int main()
{
while( ~scanf( "%d%d", &N, &M ) )
{
CN= 0;
while( N-- )
{
int c;
scanf( "%d", &c );
insert( c );
}
for( int i= 1; i<= M; ++i )
{
printf( "%d", queue[1] );
pop( );
if( i< M )
{
printf( " " );
}
}
puts( "" );
}
return 0;
}
最后是hash思想来做了,题中给了数据是-500000 到 500000, 于是在每个数据的基础上加上500000,这样开一个1000005的数组就能对应每一个数了。最后遍历一遍便能找出前M大的数了。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<time.h>
int num[1000005];
int hash( int x )
{
return x+ 500000;
}
int back( int x )
{
return x- 500000;
}
int main( )
{
int N, M, cnt, min, max;
while( ~scanf( "%d%d", &N, &M ) )
{
cnt= 0;
min= 0x7fffffff;
max= 0x7fffffff+ 1;
memset( num, 0, sizeof( num ) );
while( N-- )
{
int c;
scanf( "%d", &c );
if( min> hash( c ) )
{
min= hash( c );
}
if( max< hash( c ) )
{
max= hash( c );
}
num[ hash( c ) ]= 1;
}
for( int i= max; i>= min; --i )
{
if( num[i] )
{
cnt++;
printf( "%d", back( i ) );
if( cnt< M )
{
printf( " " );
}
if( cnt== M )
{
break;
}
}
}
puts( "" );
}
}