寒假集训2 H hdu 5265 贪心
来源:互联网 发布:济南直销软件 编辑:程序博客网 时间:2024/06/04 01:31
题目链接
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 containsn integers ai(0≤ai≤231−1) 。
For each case:
The following line contains two integers,
The following line contains
Output
For each case,output an integer means the largest score.
Sample Input
4 41 2 3 04 40 0 2 2
Sample Output
32
题目大意:给你一个序列,然后找到两个数 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 100005ll a[N];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 二分
0 0
- 寒假集训2 H hdu 5265 贪心
- 寒假集训2 I 二分 hdu 5178
- 寒假集训2 B hdu 5272 关于二进制
- 寒假集训2 c 时钟问题 hdu 5387
- 寒假集训
- 17寒假集训_贪心与最小生成树
- hdu 2072 单词数 寒假集训1 -03
- hdu 2097 Sky数 寒假集训1 06
- HDU-2089 不要62 寒假集训1 08
- hdu 2094 产生冠军 寒假集训1 09
- 寒假集训02 J hdu 5303 DP+枚举
- 寒假集训小记
- 寒假集训后记
- 寒假集训.Reverse Root
- 寒假集训.Rope
- 寒假集训.Discrete-Function
- 寒假集训.ID Codes
- 寒假集训.Intersection
- 业余07—PHD内涵
- Fragment中 onActivityResult不响应 + 有关onActivityResult提前调用的问题
- POJ 3087 - Shuffle'm Up
- Codeforces Round #339 (Div. 2) (A 高精度)
- Android 高仿微信6.0主界面 带你玩转切换图标变色
- 寒假集训2 H hdu 5265 贪心
- JavaScript事件处理
- HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
- 【应用】顺序表的就地逆置
- 在canvas上实现3D效果
- 树莓派穿透内网
- 2.7volatile关键字
- Json数据解析
- 事物