您的位置:首页 > 其它

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

由于序列中的数可能超过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)。注意一些特殊情况如同一个位置不能多次选。


#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; }

  


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: