Description
You are given a sequence a consisting of n integers. Find the maximum possible value of (integer remainder of ai divided by aj), 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.
Sample Input
Input
3 3 4 5
Output
2 题意:就是让你求a[j] > a[i]下a[j]%a[i]的最大值 第一种思路:通常我们是对n个数进行暴力这样的话肯定会超时的,所以我们换个思路进行暴力,看每个数的最大为10^6,那么我们就从2到最大的开始枚举,输入的时候处理为在第几个数就是几,然后进行暴力, 代码:第二种思路是二分:每次找到a[i]的倍数大于等于的数的下标-1的数,然后进行判断最大余数#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <vector> using namespace std; int n; int a[3000000]; int max1 = 2000000; int main() { scanf("%d",&n); memset(a,0,sizeof(a)); for(int i = 0; i < n; i++) { int d; scanf("%d",&d); a[d] = d; } for(int i = 2; i < max1; i++) { if(a[i] != i) { a[i] = a[i-1]; } }//这个地方的处理就是说在找到a[i]的倍数的时候,确定他的前一位是最大比他小的数, int tol = 0; for(int i = 2; i < max1; i++) { if(a[i] == i) { for(int j = 2*i-1; j < max1; j += i) { if(a[j] > a[i]){ tol = max(tol,a[j]%a[i]); } } } } printf("%d\n",tol); return 0; }
AC代码:#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <vector> using namespace std; int n; int a[3000000]; int main() { scanf("%d",&n); memset(a,0,sizeof(a)); for(int i = 0; i < n; i++) { scanf("%d",&a[i]); } sort(a,a+n); int tol = 0; for(int i = 0; i < n; i++) { if(i > 0 && a[i]==a[i-1]){ continue; } int k = a[n-1]/a[i]+1; for(int j = 2; j <= k; j++) { int s = lower_bound(a+i,a+n,a[i]*j)-a-1; if(a[s]%a[i] > tol) { tol = a[s]%a[i]; } } } printf("%d\n",tol); return 0; } 二分二分,奇葩的东西!!!