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数组。

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