您的位置:首页 > 其它

寒假集训2 H hdu 5265 贪心

2016-01-15 16:11 387 查看

题目链接

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


题目大意:给你一个序列,然后找到两个数 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
;

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 二分

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: