贪心/二分查找 BestCoder Round #43 1002 pog loves szh II
1 /*
2 贪心/二分查找:首先对ai%=p,然后sort,这样的话就有序能使用二分查找。贪心的思想是每次找到一个aj使得和为p-1(如果有的话)
3 当然有可能两个数和超过p,那么an的值最优,每次还要和an比较
4 注意:不能选取两个相同的数
5 反思:比赛时想到了%p和sort,lower_bound,但是还是没有想到这个贪心方法保证得出最大值,还是题目做的少啊:(
6 */
7 #include <cstdio>
8 #include <algorithm>
9 #include <cstring>
10 #include <cmath>
11 using namespace std;
12
13 typedef long long ll;
14 const int MAXN = 1e5 + 10;
15 const int INF = 0x3f3f3f3f;
16 ll a[MAXN];
17
18 int main(void) //BestCoder Round #43 1002 pog loves szh II
19 {
20 // freopen ("B.in", "r", stdin);
21
22 int n; ll p;
23 while (scanf ("%d%I64d", &n, &p) == 2)
24 {
25 for (int i=1; i<=n; ++i) {scanf ("%I64d", &a[i]); a[i] %= p;}
26 sort (a+1, a+1+n);
27
28 ll ans = 0;
29 for (int i=1; i<=n; ++i)
30 {
31 int pos = lower_bound (a+1+i, a+1+n, p - a[i]) - a; pos--;
32 if (pos <= n && pos != i) ans = max (ans, (a[i] + a[pos]) % p);
33 if (i != n) ans = max (ans, (a[i] + a[n]) % p);
34 }
35
36 printf ("%I64d\n", ans);
37 }
38
39 return 0;
40 }
编译人生,运行世界!