题目传送门:
http://acm.hdu.edu.cn/showproblem.php?pid=1029
看来写这类题目必须要创新的思路,纯粹的写循环很容易被大数据爆掉。下面是一份超时代码,目前还没有发现原因,没有死循环,目测是数据量大的原因?
#include<stdio.h>
#include<string.h>
#include<algorithm>
//#define LOCAL
int number[999999];
int times[999999];
using namespace std;
int main(){
#ifdef LOCAL
freopen("input.txt","r",stdin);
#endif // LOCAL
//超时代码
int N=0;
while(scanf("%d",&N)!=EOF){
memset(times,0,sizeof(times));
for(int i=0;i<N;i++){
scanf("%d",&number[i]);
}
for(int i=0;i<N;i++)
for(int j=0;j<N;j++){
if(number[i]== number[j])
times[i]++;
}
for(int i=0;i<N;i++){
if(times[i]>=((N+1)/2)){
printf("%d\n",number[i]);
break;
}
}
}
return 0;
}
下面是简洁的快排代码。
#include<stdio.h>
#include<string.h>
#include<algorithm>
//#define LOCAL
int number[999999];
int times[999999];
using namespace std;
int main(){
#ifdef LOCAL
freopen("input.txt","r",stdin);
#endif // LOCAL
//方法二 快排序
/*int N=0;
while(scanf("%d",&N)!=EOF){
for(int i=0;i<N;i++){
scanf("%d",&number[i]);
}
sort(number,number+N);
printf("%d\n",number[((N+1)/2)]); //注意加括号,方括号优先级高
}
return 0;
}
另外值得注意的是数组方括号的优先级比较高,里面的运算最好加括号。