codeforces 484 B Maximum Value (暴力乱搞)

题目链接 题意:给出n个元素的序列,求出最大的a[i]%a[j] (i>=j) 思路:没思路。。。。

Let us iterate over all different _a__j_. Since we need to maximize ![](http://codeforces.com/predownloaded/78/b3/78b367327f7d7a7eba50f5e1ebfaf0cb199e1837.png) , then iterate all integer _x_ (such_x_ divisible by _a__j_) in range from 2_a__j_ to _M_, where _M_ — doubled maximum value of the sequence. For each such _x_ we need to find maximum _a__i_, such _a__i_ < _x_. Limits for numbers allow to do this in time _O_(1) with an array. After that, update answer by value ![](http://codeforces.com/predownloaded/78/b3/78b367327f7d7a7eba50f5e1ebfaf0cb199e1837.png) . Total time complexity is _O_(_nlogn_ + _MlogM_)

题解也没有特别懂。。。感觉和筛法有点类似。

不过学到了一个o(1)时间得到小于x的最大数是多少的做法。

Sort the array and just maintain another array `A` of `10^6` elements where`index i stores element just smaller than i`

For example consider sorted array [2,4,7,11], then

A(0 indexed) will be [-1,-1,-1,2,2,4,4,4,7,7,7,7,11...]

-1 means no element is smaller than i.

见代码中的b数组。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年03月31日 星期四 14时23分39秒
 4File Name :code/cf/problem/484B.cpp
 5************************************************ */
 6
 7#include <cstdio>
 8#include <cstring>
 9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25#define pi pair < int ,int >
26#define MP make_pair
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=1E6+7;
34int b[2*N];
35int n ;
36int main()
37{
38	#ifndef  ONLINE_JUDGE 
39	freopen("code/in.txt","r",stdin);
40  #endif
41	cin>>n;
42	ms(b,-1);//b[i]表示比小于等于a[i]的元素里最大的。
43	for ( int i = 1 ; i <= n ; i++)
44	{
45	    int x;
46	    cin>>x;
47	    b[x] = x;
48	}
49	for ( int i = 1 ; i <2*N ; i++) if (b[i]==-1) b[i] = b[i-1];
50//	for ( int i = 1 ; i <= 20 ;  i++) cout<<b[i]<<" ";
51	int ans = 0 ;
52	for ( int j = 1 ; j < N ; j++)
53	    if (b[j]==j)
54		for ( int i = j-1 ; i < 2*N ; i+=j)
55		    if (j<=b[i]&&ans<b[i]%j) ans = b[i] % j ;
56
57	cout<<ans<<endl;
58
59  #ifndef ONLINE_JUDGE  
60  fclose(stdin);
61  #endif
62    return 0;
63}