题目链接:
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.
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).
Print the answer to the problem.
3
3 4 5
2
题意:
给n个数,要求算出最大的a[i]%a[j]的值,其中a[i]>=a[j];
思路:
可以枚举a[j],然后找出它的所有倍数,然后再在序列中找到小于它且最接近它的数.然后就是这个阶段里面最大的值了;
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <bits/stdc++.h> #include <stack> #include <map> using namespace std; #define For(i,j,n) for(int i=j;i<=n;i++) #define mst(ss,b) memset(ss,b,sizeof(ss)); typedef long long LL; template<class T> void read(T&num) { char CH; bool F=false; for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar()); for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar()); F && (num=-num); } int stk[70], tp; template<class T> inline void print(T p) { if(!p) { puts("0"); return; } while(p) stk[++ tp] = p%10, p/=10; while(tp) putchar(stk[tp--] + '0'); putchar('\n'); } const LL mod=1e9+7; const double PI=acos(-1.0); const int inf=1e9; const int N=2e5+20; const int maxn=1e6+220; const double eps=1e-12; int a[N],n,vis[maxn]; int main() { read(n); For(i,1,n)read(a[i]); sort(a+1,a+n+1); int ans=0; for(int i=1;i<=n;i++) { if(a[i]==a[i-1])continue; int pos=i; for(int k=2; ;k++) { int h=k*a[i]; int l=pos+1,r=n; while(l<=r) { int mid=(l+r)>>1; if(a[mid]>=h)r=mid-1; else l=mid+1; } pos=r; ans=max(ans,a[pos]%a[i]); if(h>=maxn)break; } } cout<<ans<<endl; return 0; }