zoj 2132 the most frequent number

the  most frequent number

CE: Gcc注释 用/**/

MLE: 快排 取中位数

/*zoj 2132 the most frequent number
quick sort
*/
# include <stdio.h>
# include <stdlib.h>
# define MAXN 250005

int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int a[MAXN];
int L, i;
while (scanf("%d", &L)==1)
{
for (i=0; i<L; ++i)
scanf("%d", &a[i]);
qsort(a, L, sizeof(int), compare);
printf("%d\n",a[L/2]);
}
return 0;
}

看了别人的代码,

/*
from 百度空间 kobeddshow
http://hi.baidu.com/kobeddshow/blog/item/26bc91ad166ba09246106439.html
*/
# include<stdio.h>
int main()
{
int n,a,i,ans,k;
while(scanf("%d",&n) != EOF )
{
k = 0;
for(i=0; i<n; i++)
{
scanf("%d",&a);
if (k == 0) ans=a, k=1;
else if(ans == a) ++k;
else --k;
}
printf("%d\n",ans);
}
return 0; /*没有这一行,提示程序非零退出 */
}

这个方法充分利用了要求的数比总数一半还多这个条件:只有比一半多,才能保证保留要求的ans,比一半少一个都不行。
看书算法技巧方面的不够多,做题也是刚开始,要坚持不懈!

TLE: 自定义快排 取中位数

View Code
/*zoj 2132 the most frequent number
quick sort
*/
# include <stdio.h>
# include <stdlib.h>
# define MAXN 250005
void quick_sort(int *a, int left, int right);
int main()
{
int a[MAXN];
int L, i;
while (scanf("%d", &L)==1)
{
for (i=1; i<=L; ++i)
scanf("%d", &a[i]);
quick_sort(a, 1, L);
printf("%d\n",a[L/2+1]);
}
return 0;
}
void quick_sort(int *a, int left, int right)
{
int tmp, i, last;
if (left >= right) return;
tmp = a[left];
a[left] = a[(left+right)>>1];
a[(left+right)>>1] = tmp;
last = left;
for (i = left+1; i <= right; ++i)
if (a[i]<a[left] && (++last)!=i) /*短路*/
{
tmp = a[last];
a[last] = a[i];
a[i] = tmp;
}
tmp = a[last];
a[last] = a[left];
a[left] = tmp;
quick_sort(a, left, last-1);
quick_sort(a,last+1, right);
}

你可能感兴趣的:(number)