pog loves szh II

http://acm.hdu.edu.cn/showproblem.php?pid=5265              

                                                    pog loves szh II

                                 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
                                                   Total Submission(s): 3208    Accepted Submission(s): 890

Problem Description

Pog and Szh are playing games.There is a sequence with n numbers, Pog will choose a number A from the sequence. Szh will choose an another number named B from the rest in the sequence. Then the score will be (A+B) mod p.They hope to get the largest score.And what is the largest score?

Input

Several groups of data (no more than 5 groups,n≥1000).
For each case: 
The following line contains two integers,n(2≤n≤100000),p(1≤p≤231−1)。
The following line contains n integers ai(0≤ai≤231−1)。

Output

For each case,output an integer means the largest score.

Sample Input

4 4 1 2 3 0 4 4 0 0 2 2

Sample Output

3 2

 

题解:

题意很简单,找出n个数中的两个,使它们的和模p之后最大。最基本想法当然是暴力枚举所有情况,然后选出最大的。但是注意到n的范围,最大1e5,暴力枚举绝对tle。后来我想到了二分法,但因为一个很脑残的错误wa了10遍(汗~)。下面贴代码。

#include<bits/stdc++.h>
using namespace std;
int n,p;
long long ve[100005];
bool cmp(int a,int b)
{
    return a>b;
}
int main()
{
    while(~scanf("%d%d",&n,&p))
    {
        memset(ve,-1,sizeof(ve));//这一步很重要,并且不能初始化为0,只能是负数,因为读入的数据中模p之后可能有为0的,当时因为没有这一步wa了10发
        for (int i=0; i<n; ++i)
        {
            scanf("%lld",&ve[i]);
            ve[i]%=p;
        }
        sort(ve,ve+n,cmp);
        long long temp;
        long long mx=(ve[0]+ve[1])%p;
        for (int i=0; i<n; ++i)
        {
            temp=*upper_bound(ve+i+1,ve+n,p-ve[i],greater<int>() );//如果没有找到刚好小于p-ve[i]的数,会返回v[n]
            if (temp==-1)
                temp=-1e18;
            mx=max(mx,ve[i]+temp);
        }
        printf("%lld\n",mx);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值