Description
You are given a sequence a consisting of n integers. Find the maximum possible value of (integer remainder
of ai divided byaj), where 1 ≤ i, j ≤ n and ai ≥ aj.
Input
The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105).
The second line contains n space-separated integers ai (1 ≤ ai ≤ 106).
Output
Print the answer to the problem.
题意:输入n,再输入n个数,求这n个数内ai对aj取余且ai>=aj最大的余数。
思路:如果暴力枚举铁定超时。具体思路看一下代码即代码旁的注释。
技巧:对于卡时间的题目,要注意取地址符和判断的语句,取地址符和判断也是需要一定时间的,当时间要求比较严
格时,尽量少一些判断语句,而取地址符对于数组来说是可以省略,不管是整型也好还是字符串型【例:
scanf("%d",sum+i),sum是数组名,i是指数组下标】。
Sample input
3
3 4 5
Sample output
2
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>
#define INF 0x3f3f3f3f
using namespace std;
int a[2000005],num;
bool ha[2000005];
int main()
{
//freopen("abc.text","r",stdin);
int n;
while(~scanf("%d",&n))
{
memset(ha,0,sizeof(ha));
memset(a,0,sizeof(a));
int mmax=-1;
for(int i=1; i<=n; i++)
{
scanf("%d",&num);
if(num>mmax)
mmax=num; //记录所出现的最大的数
ha[num]=true; //用哈希表记录哪些数出现过
}
for(int i=1; i<=mmax*2; i++)
{
if(ha[i-1]) //用a数组记录最接近其下标且小于其下标的数
a[i]=i-1;
else
a[i]=a[i-1]; //有的时候要想到用动规,不然用暴力太浪费时间了
}
int ans=-1;
for(int i=1; i<=mmax*2; i++) //枚举出现过的数
{
if(!ha[i])
continue;
for(int j=2; i*j<=mmax*2; j++) //只要出现了则根据它的倍数找对其取余的余数
ans=max(ans,a[i*j]%i);
}
printf("%d\n",ans);
}
return 0;
}<strong>
</strong>