pog loves szh II
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1158 Accepted Submission(s): 328
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) 。
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
普通想法超时。
输入时对p取余,然后排序,判断最后两个数与p的大小,如果最后两个数小于p就是最后两个数了,否则将最后两个数和对p取余放在ans中,然后枚举比较。
枚举也是有技巧的,第一个从最大开始,另一个从最小开始,用一个now,记录一下当前的位置。
还有一点只要是和大于p,那么取余肯定比最后两个数的和小。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[100000+5];
int main()
{
int n,p,x,ans;
while(scanf("%d%d",&n,&p)!=EOF)
{
for(int i=0;i<n;i++)
{
scanf("%d",&x);
a[i]=x%p;
}
sort(a,a+n);
if(a[n-1]<p-a[n-2])
{
printf("%d\n",a[n-1]+a[n-2]);
}
else
{
ans=a[n-1]-p+a[n-2];
int now=0;
for(int i=n-1;i>=0;i--)
{
for(int j=now;j<i;j++)
{
if(a[i]<p-a[j])
ans=max(a[i]+a[j],ans);
else
{
if(j>0)
now=j-1; //都是从大到小排列的,所以i-1没必要从0开始匹配,只需从j-1开始判断就行了。
break;
}
if(ans==p-1) break;
}
if(ans==p-1) break;
}
printf("%d\n",ans);
}
}
return 0;
}