pog loves szh II
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2106 Accepted Submission(s): 606
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)。
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
有n个数,从这n个数中选出两个数,不能同样,使得两个数相加取模后的值最大。
能够先进行排序,然后用线性的方法找最大。
排序之前先对全部的数取一遍模。因为模运算的性质。这并不会影响结果。(a+b)%mod==( a%mod+b%mod )%mod。
能够先取排序之后的最后两个数,假设他们的和小于模p。直接输出他们的和,由于这一定是最大的。
否则的话还得找,设置 l 从0開始往后,r从n-1開始往前,对于每一个 l 。找到最右边的r,使得a[ l ]+a[ r ]
这时r就不用往前了,由于往前的话值一定会变小,每次找到之后,更新最大值,同一时候 l 往前一位,可是 r 不用动,
由于数组是有序的。(细致想想就知道了)。这样时间复杂度就控制在线性阶了。
另外2^31-1是2147483647,有符号整型能表示的最大值.
#include