hdu 5265 技巧题 O(nlogn)求n个数中两数相加取模的最大值
来源:互联网 发布:SSL协议所使用的端口是 编辑:程序博客网 时间:2024/06/08 17:02
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
Problem Description
Pog and Szh are playing games.There is a sequence withn 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 containsn integers ai(0≤ai≤231−1) 。
For each case:
The following line contains two integers,
The following line contains
Output
For each case,output an integer means the largest score.
Sample Input
4 41 2 3 04 40 0 2 2
Sample Output
32
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;}
0 0
- hdu 5265 技巧题 O(nlogn)求n个数中两数相加取模的最大值
- n个数 取任意个数相加求和的个数
- 递归求n个数相加的和
- 求n个数的最大值和最小值
- 递归4.求n个数的最大值
- n个数,分两组,使相加的两组数最大值最小
- 求数组的最大子段和(O(N^3)-->O(N^2)-->O(NlogN)-->O(N))
- 求数组的第K小数,O(nlogn) 和 O(N)的算法
- 求子数组的最大和(O(n)和分治法O(nlogn))
- 求子数组的最大和(O(n)和分治法O(nlogn))
- oj 2725: 递归--求n个数的最大值
- 蓝桥杯训练:递归——求N个数的最大值
- 求n个数中两数异或的最大值(字母树)
- 求最大值最小值的方法 时间复杂度O(n)
- 寒假集训3 c 求N个数中 取两个数的最大公约数 hdu 5207
- n个数中取最大值与最小值
- 找出n个数组成的最长单调递增子序列( 动态规划O(nlogn) )
- hdu 求n个数的最小公倍数
- Java介绍+注释+环境变量笔记-第1天
- fragment嵌套viewpager嵌套 关于不能正常显示问题
- C++多态性:虚函数的调用原理
- 【Util】iText,iTextAsian,中文显示
- C++输入输出流格式控制
- hdu 5265 技巧题 O(nlogn)求n个数中两数相加取模的最大值
- AlertDialog
- HDU 2955
- error C2664: 'CWnd::MessageBoxW' : cannot convert parameter 1 from 'char *' to 'LPCTSTR'的解决方法
- windows sc命令注意点
- Gym 100187E - Two Labyrinths
- 用&& php写的条件语句-三种条件语句
- 1!+2!+3!+...n!Java史上最简洁的阶乘算法!!!
- android service startService与bindService的区别