HDU 5265 pog loves szh II

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


二分


#include<cstdio>
#include<cstring>
#include<vector>
#include<iostream>
#include<queue>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<string>
using namespace std;
const int maxn = 100005;
int T, n, m, ans;
int a[maxn], b[maxn];

int main()
{
    //scanf("%d", &T);
    while (cin >> n >> m)
    {
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            a[i] = a[i] % m;
            b[i] = m - a[i] - 1;
        }
        sort(a, a + n);
        sort(b, b + n);
        ans = a[n - 1] - m + a[n - 2];
        if (ans < 0) ans += m;
        for (int i = 0; i < n; i++)
        {
            int k = n - 1 - (lower_bound(b, b + n, a[i]) - b);
            if (k == i) k--;
            if (k < 0) continue;
            if (a[i] + a[k] > ans) ans = a[i] + a[k];
        }
        printf("%d\n", ans);
    }
}


你可能感兴趣的:(HDU 5265 pog loves szh II)