hdu 5265 技巧题 O(nlogn)求n个数中两数相加取模的最大值
2017-08-02 11:57
323 查看
pog loves szh II
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2106 Accepted Submission(s): 606
[align=left]Problem Description[/align]
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?
[align=left]Input[/align]
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)。
[align=left]Output[/align]
For each case,output an integer means the largest score.
[align=left]Sample Input[/align]
4 4 1 2 3 0 4 4 0 0 2 2
[align=left]Sample Output[/align]
3 2
[align=left]Source[/align]
field=problem&key=BestCoder+Round+%2343&source=1&searchmode=source">BestCoder Round #43
有n个数,从这n个数中选出两个数,不能同样,使得两个数相加取模后的值最大。
能够先进行排序,然后用线性的方法找最大。
排序之前先对全部的数取一遍模。因为模运算的性质。这并不会影响结果。(a+b)%mod==( a%mod+b%mod )%mod。
能够先取排序之后的最后两个数,假设他们的和小于模p。直接输出他们的和,由于这一定是最大的。
否则的话还得找,设置 l 从0開始往后,r从n-1開始往前,对于每一个 l 。找到最右边的r,使得a[ l ]+a[ r ]<p,
这时r就不用往前了,由于往前的话值一定会变小,每次找到之后,更新最大值,同一时候 l 往前一位,可是 r 不用动,
由于数组是有序的。(细致想想就知道了)。这样时间复杂度就控制在线性阶了。
另外2^31-1是2147483647,有符号整型能表示的最大值.
#include<map> #include<vector> #include<cstdio> #include<iostream> #include<cstring> #include<string> #include<algorithm> #include<cmath> #include<stack> #include<queue> #include<set> #define inf 0x3f3f3f3f #define mem(a,x) memset(a,x,sizeof(a)) using namespace std; typedef long long ll; typedef pair<int,int> pii; inline ll in() { ll res=0;char c; while((c=getchar())<'0' || c>'9'); while(c>='0' && c<='9')res=res*10+c-'0',c=getchar(); return res; } ll a[100010]; int main() { int n,p; while(~scanf("%d%d",&n,&p)) { for(int i=0;i<n;i++) { a[i]=in()%p; } sort(a,a+n); //排序 ll mx=(a[n-1]+a[n-2])%p; int l=0,r=n-1; while(l<r) { while(r>=0 && a[l]+a[r]>=p)r--; //防止r<0 if(l<r) mx=max(mx,a[l]+a[r]); //r不能小于等于l l++; } cout<<mx<<endl; } return 0; }
相关文章推荐
- hdu 5265 技巧题 O(nlogn)求n个数中两数相加取模的最大值
- HDU 1431 素数回文(打表+技巧,最大回文素数为9989899!!!)
- hdu1864最大报销额度(01背包)- 把小数化整数技巧
- LeetCode 02. 两数相加(链表) 03.最大不重复的字符串
- HDU 5265 pog loves szh II (技巧)
- hdu 5207 求数组中任取两数的gcd最大值(灵活题)
- hdu 1068 Girls and Boys(二分图匹配---最大独立点集)
- HDU 5280 Senior's Array 最大区间和
- hdu 3829 Cat VS Dog(最大独立集)
- HDU — 4240 Route Redundancy(最大流)
- hdu 1530 Maximum Clique——最大团
- HDU - 1269【Tarjan最大强连通分量】
- hdu 1505(dp求最大子矩阵)
- hdu 5306 区间取min和询问区间和及最大数
- 单排leetcode(python3)-两数相加
- HDU 1025 Constructing Roads In JGShining's Kingdom(最长上升子序列O(nlogn))
- HDU1845 Jimmy’s Assignment 984ms 飘过啊 汗死 二分匹配最大匹配数
- DP--HDU 1003(最大子串和)
- hdu 3416 Marriage Match IV 【网络最大流+最短路】
- 给一个数组,元素都是整数(有正数也有负数),寻找连续的元素相加之和为最大的序列。