HDU5265——贪心——pog loves szh II
2015-06-08 19:41
281 查看
[align=left]ProblemDescription[/align]
PogandSzhareplayinggames.Thereisasequencewith$n$numbers,PogwillchooseanumberAfromthesequence.SzhwillchooseananothernumbernamedBfromtherestinthesequence.Thenthescorewillbe$(A+B)$mod$p$.Theyhopetogetthelargestscore.Andwhatisthelargestscore?
[align=left]Input[/align]
Severalgroupsofdata(nomorethan$5$groups,$n\geq1000$).
Foreachcase:
Thefollowinglinecontainstwointegers,$n(2\leqn\leq100000)$,$p(1\leqp\leq2^{31}-1)$。
Thefollowinglinecontains$n$integers$a_i(0\leqa_i\leq2^{31}-1)$。
[align=left]Output[/align]
Foreachcase,outputanintegermeansthelargestscore.
[align=left]SampleInput[/align]
44
1230
44
0022
[align=left]SampleOutput[/align]
3
2
[align=left]Source[/align]
BestCoderRound#43
[align=left]Recommend[/align]
hujie|Wehavecarefullyselectedseveralsimilarproblemsforyou:52675266526352625261
#include<cstdio>
#include<cstring>
#include<algorithm>
usingnamespacestd;
longlonga[100100];
intmain()
{
intn;
longlongp;
while(~scanf("%d%lld",&n,&p)){
for(inti=1;i<=n;i++){
scanf("%lld",&a[i]);
a[i]%=p;
}
sort(a+1,a+n+1);
longlongmax1=(a
+a[n-1])%p;
intnow=n;
for(inti=1;i<now;i++){
max1=max(max1,(a[i]+a[now])%p);
if(a[i]+a[now]>=p){
now--;
i--;
}
}
printf("%lld\n",max1);
}
return0;
}
PogandSzhareplayinggames.Thereisasequencewith$n$numbers,PogwillchooseanumberAfromthesequence.SzhwillchooseananothernumbernamedBfromtherestinthesequence.Thenthescorewillbe$(A+B)$mod$p$.Theyhopetogetthelargestscore.Andwhatisthelargestscore?
[align=left]Input[/align]
Severalgroupsofdata(nomorethan$5$groups,$n\geq1000$).
Foreachcase:
Thefollowinglinecontainstwointegers,$n(2\leqn\leq100000)$,$p(1\leqp\leq2^{31}-1)$。
Thefollowinglinecontains$n$integers$a_i(0\leqa_i\leq2^{31}-1)$。
[align=left]Output[/align]
Foreachcase,outputanintegermeansthelargestscore.
[align=left]SampleInput[/align]
44
1230
44
0022
[align=left]SampleOutput[/align]
3
2
[align=left]Source[/align]
[align=left]Recommend[/align]
hujie|Wehavecarefullyselectedseveralsimilarproblemsforyou:
由于序列中的数可能超过P,所以将所有的数读入后进行取模操作。之后将取模后的所有数从小到大排序。题目要求我们求不同位置的两个数的和在取模意义下的最大值,而现在所有数都是小于P且排好序的。因此设我任意选了两个数是X和Y,显然0≤X+Y≤2P−2。若X+Y<P,则这次选数的答案就是X+Y,若X+Y≥P,则答案是X+Y−P。 那么我们可以这样做:将其中最大的两个数字相加取模,设为一个可能的答案记录在ANS中。这个答案是第二种情况的最大值。再对排序好的序列进行枚举,对每个枚举到的数,找出最大的数,使这个数与枚举到的数相加后的和最大且小于P,将之记为可能的答案并于之前找到的最大值ANS进行比较。这个答案是第一种情况中的可能的最大值。而普通的枚举是要超时的,但是我们发现如果从小到大枚举第一个数,那么另一个匹配的数显然是从大到小的,因此可以用一个NOW记录当前另一个匹配的数的位置,每次枚举时NOW递减至符合条件。可以做到O(n)的时间复杂度。 综上所述,时间复杂度为快速排序的O(nlogn),空间复杂度为O(n)。注意一些特殊情况如同一个位置不能多次选。
相关文章推荐
- 智慧树
- Leetcode--RegularExpressionMatching
- java中volatile关键字的含义
- caffe学习,持续更新
- 对三层架构的理解
- 嵌入式的 gdb 远程调试
- 搜索引擎中关键字搜索建议的实现(内附小Demo)
- Android 5.0 documentation CHM 版本 下载
- 常用的shell脚本
- python 函数嵌套支持多层嵌套,但不支持嵌套并列函数调用
- 函数指针与指针函数
- 二维RMQ模板
- Greenplum 数据库安装部署(生产环境)
- 如何阅读 Redis 源码?
- 支付宝手机网页支付即时到账接口
- 多线程之CompletionService使用
- Android 网络请求实现
- 计算机整数乘积计算
- position: static absolute relative
- C语言 gets()和scanf()函数的区别