首先看看题目:
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[i] < a[j], 求出a[j] % a[i]的最大值。
好了,看见2*10^5这么大的数字,首先就是什么也不管,暴力!!!!卧槽,我就不信了,暴力 = =
然后就是gg了的暴力代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAX = 5000010;
int a[MAX];
int main()
{
int m;
while(scanf("%d", &m) != EOF)
{
for(int i = 0; i < m; i++)
{
cin >> a[i];
}
sort(a, a+m);
int ans = 0;
for(int i = 0; i < m-1; i++)
{
for(int j = i+1; j < m; j++)
{
if(ans < a[j] % a[i])
{
ans = a[j] % a[i];
}
}
}
printf("%d\n", ans);
}
return 0;
}
T T然后就是说,想更优化的办法。
报警了 = =;
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
const int maxn = 2000000+100;//数组开小了,runtime error,不开心
int a[maxn];
int main()
{
int m;
memset(a, -1, sizeof(a));
scanf("%d", &m);
for(int i = 0; i < m; i++)
{
int x;
scanf("%d", &x);
a[x] = x;
}
for(int i = 0; i < maxn; i++)
{
if(a[i] != i)//表示不在数组里面
{
a[i] = a[i-1];
}
}
int ans = 0;
for(int i = 2; i < maxn; i++)
{
if(a[i] == i)
{
for(int j = 2*i-1; j < maxn; j+=i)
{
if(ans < a[j] % i && i < a[j])
{
ans = a[j] % i;
}
}
}
}
printf("%d\n", ans);
return 0;
}