二分

本文介绍了一种解决特殊二分查找问题的游戏算法,玩家通过选择序列中的两个数求和并取模获得分数,目标是找到能获得的最大分数。文章提供了一个C++实现示例,该算法首先对输入序列进行排序,然后采用二分查找的方法确定最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

注意:特殊的二分

 

 

#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
    long long int n,p,x;
    long long int a[100000];
    int i,j;
    long long int r,l,mid;
    long long int max;
    while(scanf("%lld %lld",&n,&p)!=EOF)
    {
        for(i=0; i<n; i++)
        {
            scanf("%lld",&a[i]);
            //printf("%lld ",a[i]);
           if(a[i]>p)
                a[i]=a[i]%p;
        }
        sort(a,a+n);
        max=(a[n-1]+a[n-2])%p;
        l=0;
        r=n-1;
       // printf("\n%lld ",a[n-1]);
        while(r-l!=0)
        {
           // mid=(l+r)/2;
            x=(a[l]+a[r]);
            if(x%p>max)
                max=x%p;
                //printf("\n%lld",max);
            if(x>=p)
                r--;
            if(x<p)
                l++;
        }
        printf("%lld\n",max);

    }

    return 0;
}


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值