寒假集训2 H hdu 5265 贪心

题目链接

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



题目大意:给你一个序列,然后找到两个数 A B   使得  A+B  % MOD最大


解析:由于数列中的值可能大于P,所以将所有的数读入后进行取模操作。之后将取模后的所有数从小到大排序。题目要求我们求不同位置的两个数的和在取模意义下的最大值,而现在所有数都是小于P且排好序的。因此设我任意选了两个数是X和Y,显然0≤X+Y≤2P−2。若X+Y<P,则这次选数的答案就是X+Y,若X+Y≥P,则答案是X+Y−P。

我们可以这样做:将其中最大的两个数字相加取模,设为一个可能的答案记录在max中。这个答案是第二种情况的最大值。再对排序好的序列进行枚举,对每个枚举到的数,找出最大的数,使这个数与枚举到的数相加后的和最大且小于P,将之记为可能的答案,并于之前找到的最大值max进行比较。这个答案是第一种情况中的可能的最大值。

而普通的枚举是要超时的,所以我们记下第一个枚举的数,设l = 0, 即最大的数,然后从后向前依次求和, 当a[i] + a[l] >= p时,需要缩小a[i] + a[l],所以i++, l++。
综上所述,时间复杂度为快速排序的O(nlogn),空间复杂度为O(n)。


<span style="font-size:14px;">#include <iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
using namespace std;
#define ll long long
#define N 100005
ll a[N];

bool cmp(int a, int b)
{
    return a > b;
}

int main()
{
   //freopen("E:\input.txt", "r", stdin);
    int n, p;
    int i;
    while ((scanf("%d%d", &n, &p)) != EOF)
    {
        for (i = 0; i < n; i++)
        {
            scanf("%I64d", &a[i]);
            a[i] = a[i] % p;
        }
        sort(a, a+n, cmp);
        ll max1 = (a[0] + a[1]) % p;
        int l = 0;
        for (i = n - 1; i > l; i--)
        {
            max1 = max(max1, (a[l] + a[i]) % p);
            if (a[i] + a[l] >= p)
            {
                i++;  //值变小
                l++;   //值变小
            }
        }
        printf("%I64d\n", max1);
    }
    return 0;
}
</span>


相关博客:

hdu 5265(水)

HDU5265——贪心——pog loves szh II

hdu 5265 pog loves szh II 二分




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值