codeforces D. Maximum Value

约定不等于承诺〃 2022-07-24 09:16 283阅读 0赞

D. 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 78b367327f7d7a7eba50f5e1ebfaf0cb199e1837.png (integer remainder of a**i divided bya**j), where 1 ≤ i, j ≤ n and a**i ≥ a**j.

Input

The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·105).

The second line contains n space-separated integers a**i (1 ≤ a**i ≤ 106).

Output

Print the answer to the problem.

Examples

input

  1. 3
  2. 3 4 5

output

  1. 2

题意: 给你n个数, 求最大的ai%aj的值.

分析: 可以将原先数组排个序, 然后去重, 用类似于埃氏筛选的方法对于每个数a[i]枚举它的倍数, 然后对于每个倍数x, 找小于x的最大的a[k]; 那么a[i]-(x-a[k])就是a[k]模a[i]的值, (x-a[k])是最小的, 因此a[i]-(x-a[k])就是最大的, 不断更新答案就行啦.

开始是用二分找小于x的最大的值, 后来发现可以用一个数组来做;

  1. #include<bits/stdc++.h>
  2. #define inf 0x3f3f3f3f
  3. using namespace std;
  4. typedef long long ll;
  5. typedef pair<int,int> pii;
  6. const int N=2000010,MOD=1e9+7;
  7. int a[200020];
  8. int pre[N];
  9. bool have[N];
  10. int main()
  11. {
  12. int n;cin>>n;
  13. for(int i=0;i<n;i++) scanf("%d",a+i),have[a[i]]=1;
  14. sort(a,a+n);
  15. n = unique(a,a+n)-a;
  16. int mx = a[n-1];
  17. mx<<=1;
  18. int last=0;
  19. for(int i=1;i<=mx;i++){
  20. if(!have[i]) pre[i] = last;
  21. else{
  22. pre[i]=last;
  23. last=i;
  24. }
  25. }
  26. int ans=0;
  27. int i=a[0]==1;
  28. for(;i<n;i++){
  29. for(int j=a[i]+a[i];j<mx;j+=a[i]){
  30. if(j-a[n-1]>=a[i]) break;
  31. int ret = pre[j];
  32. if(j-ret >= a[i]) continue;
  33. ans = max(ans,a[i]-(j-ret));
  34. }
  35. }
  36. cout<<ans<<endl;
  37. return 0;
  38. }

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读

    相关 CodeForces1214D

    [CodeForces1214D][] 这个题据我所知有两种比较优秀的做法. 第一种是\\(DP\\)统计每个点的路径数,然后找出必经点,再从必经点开始\\(bfs\\

    相关 CodeForces1208D

    CodeForces1208D 也是挺吓人的一道题,我一开始以为给的是每个数字前比它小的数字有几个,然后我就苦苦看不懂样例... 然后我冷静了一下,重新分析,读题,发现

    相关 Codeforces 496D

    题意 -------------------- 进行若干场比赛,每次比赛两人对决,赢的人得到1分,输的人不得分,先得到t分的人获胜,开始下场比赛,某个人率先赢下s场比赛