Codeforces 485D Maximum Value【思维+技巧枚举】
来源:互联网 发布:大数据提供价格 编辑:程序博客网 时间:2024/05/16 12:48
You are given a sequence a consisting ofn integers. Find the maximum possible value of (integer remainder ofai divided byaj), where1 ≤ 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 integersai (1 ≤ ai ≤ 106).
Print the answer to the problem.
33 4 5
2
题目大意:
给你N个数,让你找到两个数Ai,Aj,使得Ai%Aj的值最大,这里需要保证Ai>Aj;
思路:
1、首先我们对数组排序&&去重。
2、然后考虑对于Ai来讲,其能够找到的Aj如果是Ai的因子数,那么一定Ai%Aj==0.如果此时Aj是Ai的最大因子数(不包括Ai本身),那么Ai%A【j+1-------->i-1】是会逐渐递减的,所以那么我们每一次找到一个因子数,那么期望的最大模值肯定要在Ai%Aj+1中选取,所以我们可以考虑O(n)枚举Ai然后sqrt(Ai)去枚举因字数,然后过程维护一个最大值即可。
总时间复杂度O(nsqrt(a【i】));
方法是对的,可惜被卡了TLE...................
那么我们考虑如何优化。
3、我们刚刚是在枚举因子数,反过来想,我们不妨枚举倍数。那么我们需要枚举1e6+1e6/2+1e6/3+1e6/4+.............1e6/1e6次。
估算一下,大概需要枚举1e7次。
那么我们枚举一个数之后,枚举其倍数,对应在数组中找到比这个倍数小的最大的数,那么ans=max(ans,这个倍数小的最大的数%枚举出来的这个数);
如果二分处理,大概也要1e8+次,实际尝试了一下,TLE了。
其实我们可以预处理出来一个数组vis【i】,表示原序列中,小于等于i的最大的数。
这里预处理O(n)就能实现,所以查询可以做到O(1);
一共1e7次左右的操作,单组数据就不会超时了。
Ac代码:
#include<stdio.h>#include<string.h>#include<math.h>#include<algorithm>#include<iostream>using namespace std;int pos[4000000];int vis[5000000];int a[500000];int main(){ int n; while(~scanf("%d",&n)) { int tot=0; int maxn=0; memset(vis,-1,sizeof(vis)); memset(pos,-1,sizeof(pos)); vis[1]=1; for(int i=1;i<=n;i++) { int x;scanf("%d",&x); vis[x]=x; } for(int i=1;i<=2000050;i++)if(vis[i]==-1)vis[i]=vis[i-1]; for(int i=1;i<=1000050;i++) { if(vis[i]==i) { for(int j=i*2;j<=2000050;j+=i) { if(vis[j-1]>i)output=max(output,vis[j-1]%i); } } } printf("%d\n",output); }}
- Codeforces 485D Maximum Value【思维+技巧枚举】
- Codeforces 485D Maximum Value【思维+数论】
- codeforces 485D. Maximum Value
- codeforces D. Maximum Value
- 51nod 1421 最大MOD值 & codeforces 485D Maximum Value(思维 数学)
- CodeForces-485D Maximum Value(暴力)
- Codeforces 484B Maximum Value——思维
- Codeforces Round #276 (Div. 2)-D. Maximum Value
- cf 485d Maximum Value 【二分】
- Maximum Value CodeForces
- 【Codeforces Round 276 (Div 2)D】【数论 正难则反 枚举倍数 二分 O(nlogn)】Maximum Value n个数大数mod小数找最大余数
- Codeforces 552D Vanya and Triangles【暴力枚举+思维】
- Codeforces 599D Spongebob and Squares【思维枚举+数学方程】
- CodeForces 484B Maximum Value
- Codeforces 484B Maximum Value
- codeforces 765D 思维
- codeForces 612D(思维)
- codeforces 673D(思维)
- 时间日期格式转换 sdutoj2246(Date类简单使用)
- (四)JUnit测试套件使用及参数化设置
- Win10+Ubuntu17.04双系统安装
- ThinkPHP3.2.3的Htmlpurifier的简易使用(不建议常用影响效率)
- 捡起那些丢掉的(记前湖之行)
- Codeforces 485D Maximum Value【思维+技巧枚举】
- 使用Django + Vue.js快速而优雅地构建前后端分离项目
- 单元二 -函数和编译处理
- codeforce round#410 D. Mike and distribution(谐星排序选择)
- GDOI模拟4.19~4.21总结
- 省赛D Let's Chat
- 绝对值排序 HDU
- 设置mybatis配置文件xml自动提示
- 设计模式--单例模式python实现