当前位置: 首页 > 工具软件 > POG > 使用案例 >

pog loves szh II

彭星津
2023-12-01

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);
    }
}
 类似资料:

相关阅读

相关文章

相关问答