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/65536K (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)。注意一些特殊情况如同一个位置不能多次选。
相关文章推荐
- HDOJ1019Least Common Multiple
- Linux Kernel(Android) 加密算法汇总(三)-应用程序调用内核加密算法接口
- SHA-1 加密算法破解现已只需要 10 天
- 10.9做题——USACO1.2/洛谷1206回文平方数(Palindromic Squares)
- 数组遍历的练习
- Python网络爬虫(Get、Post抓取方式)
- DES算法
- Python网络爬虫(Get、Post抓取方式)
- gcc 使用
- 题目:有n(n<=8)个物品需要装入盒子,形状为圆型,且物品必须紧贴盒子底部。情况类似图中所示:
- 【Foundation-86-2】#import <Foundation/NSValue.h>
- 【lnoi2013】最小距离之和
- Java内存模型
- matlab 函数句柄
- 使用绞车和3PS滑轮计数器收放klein3000托鱼
- 动态内存分配(new delete)
- 《深入理解Linux网络技术内幕》阅读笔记(二十一)
- 类和加载
- SpringAccess数据库(oracle)构造
- 纯JS实现fadeIn 和fadeOut