B. Maximum Value
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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 test(s)
input
3 3 4 5
output
2
解题报告:求一个序列中两数相除的最大余数,保证被除数大于除数。
这题我一开始做的时候是枚举除数,然后找到“除数倍数”位置的前一个位置(lower_bound),求出它的余数,但是发现不加判重就超时了,加了判重跑得也很吃力。后来听说可以用二分法求余数,自己写了一遍后,运行效率大大提高。所以以后枚举的时候要考虑是不是能够二分。
直接枚举:
/********************************/
/*Problem: codeforces #484B# */
/*User: shinelin */
/*Memory: 2100 KB */
/*Time: 639 ms */
/*Language: GNU C++ */
/********************************/
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <string>
#include <list>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <set>
#include <algorithm>
#include <cmath>
using namespace std;
#define INF 0x7fffffff
#define LL long long
vector<int> a;
int main()
{
int x, N;
scanf("%d", &N);
for (int i = 0; i < N; i ++)
{
scanf("%d", &x);
a.push_back(x);
}
sort(a.begin(), a.end());
int MaxMod = 0;
for (int i = N - 1; i >= 0; i --)
{
if(a[i] == 0 || a[i] == a[i-1]) continue; //判重
int tmp = 2 * a[i];
while(tmp <= a[N-1])
{
int k = lower_bound(a.begin(), a.end(), tmp) - a.begin();
if(k > 0 && a[k-1] % a[i] > MaxMod)
{
MaxMod = a[k-1] % a[i];
if(MaxMod == a[i] - 1)
break;
}
tmp += a[i];
}
if(a[N-1] % a[i] > MaxMod)
{
MaxMod = a[N-1] % a[i];
}
}
printf("%d\n", MaxMod);
return 0;
}
二分求余数:
/********************************/
/*Problem: codeforces #484B# */
/*User: shinelin */
/*Memory: 2100 KB */
/*Time: 109 ms */
/*Language: GNU C++ */
/********************************/
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <string>
#include <list>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <set>
#include <algorithm>
#include <cmath>
using namespace std;
#define INF 0x7fffffff
#define LL long long
vector<int> a;
int N;
bool BigMod(int d)
{
int k = lower_bound(a.begin(), a.end(), d) - a.begin();
for (int i = k; i < N; i ++)
{
if(a[i] == a[i-1]) continue;
int j = 2 * a[i];
while (j <= a[N-1])
{
int cur = lower_bound(a.begin(), a.end(), j) - a.begin();
if(cur > 0 && a[cur-1] % a[i] > d)
{
return true;
}
j += a[i];
}
if(a[N-1] % a[i] > d)
return true;
}
return false;
}
int main()
{
int x, Min, Max, Mid;
scanf("%d", &N);
for (int i = 0; i < N; i ++)
{
scanf("%d", &x);
a.push_back(x);
}
sort(a.begin(), a.end());
Min = 0;
Max = a[N-1];
while(Min < Max)
{
Mid = (Max + Min) >> 1;
if(BigMod(Mid))
{
Min = Mid + 1;
}
else
{
Max = Mid;
}
}
printf("%d\n", Min);
return 0;
}