您的位置:首页 > 其它

BestCoder Round #43 HDU5265 pog loves szh II 排序+贪心

2015-10-09 20:05 309 查看




pog loves szh II

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536
K (Java/Others)

Total Submission(s): 2150 Accepted Submission(s): 621



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


Source

BestCoder Round #43

出题人:由于序列中的数可能超过PP,所以将所有的数读入后进行取模操作。
之后将取模后的所有数从小到大排序。题目要求我们求不同位置的两个数的和
在取模意义下的最大值,而现在所有数都是小于P且排好序的。因此设我任意
P
选了两个数是XX和YY,显然0
\leq X+Y \leq 2P-20≤X+Y≤2P−2。若X+Y
< PX+Y<P,则这次选数的答案
就是X+YX+Y,若X+Y
\geq PX+Y≥P,则答案是X+Y-PX+Y−P。
那么我们可以这样做:将其中最大的两个数字相加取模,设为一个可能的答案记录在ANS中。
这个答案是第二种情况的最大值。再对排序好的序列进行枚举,对每个枚举到的数,
找出最大的数,使这个数与枚举到的数相加后的和最大且小于P,将之记为可能的答案
并于之前找到的最大值ANS进行比较。这个答案是第一种情况中的可能的最大值。而普通
的枚举是要超时的,但是我们发现如果从小到大枚举第一个数,那么另一个匹配的数显然
是从大到小的,因此可以用一个NOW记录当前另一个匹配的数的位置,每次枚举时NOW
递减至符合条件。可以做到O(n)O(n)的时间复杂度。
综上所述,时间复杂度为快速排序的O(nlogn)O(nlogn),
空间复杂度为O(n)O(n)。注意一些特殊情况如同一个位置不能多次选。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: