Bestcoder Round#43pog loves szh II

pog loves szh II

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


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, n1000 ).

For each case: 

The following line contains two integers, n(2n100000) p(1p2311)

The following line contains  n  integers  ai(0ai2311)
 

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
 
普通想法超时。
输入时对p取余,然后排序,判断最后两个数与p的大小,如果最后两个数小于p就是最后两个数了,否则将最后两个数和对p取余放在ans中,然后枚举比较。
枚举也是有技巧的,第一个从最大开始,另一个从最小开始,用一个now,记录一下当前的位置。
还有一点只要是和大于p,那么取余肯定比最后两个数的和小。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100000+5];
int main()
{
    int n,p,x,ans;
    while(scanf("%d%d",&n,&p)!=EOF)
    {
        for(int i=0;i<n;i++)
        {
            scanf("%d",&x);
            a[i]=x%p;
        }
        sort(a,a+n);
        if(a[n-1]<p-a[n-2])
        {
            printf("%d\n",a[n-1]+a[n-2]);

        }
        else
        {
            ans=a[n-1]-p+a[n-2];
            int now=0;
            for(int i=n-1;i>=0;i--)
            {
                for(int j=now;j<i;j++)
                {
                    if(a[i]<p-a[j])
                        ans=max(a[i]+a[j],ans);    
                    else
                    {
                        if(j>0)
                            now=j-1;        //都是从大到小排列的,所以i-1没必要从0开始匹配,只需从j-1开始判断就行了。
                        break;
                    }
                    if(ans==p-1) break;
                }
                if(ans==p-1) break;
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值