HDU Ignatius and the Princess IV

题目传送门:
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;
}

另外值得注意的是数组方括号的优先级比较高,里面的运算最好加括号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值