【二分】小鱼吃大鱼

链接

Luogu U138097

题目描述

有n个数,选择两个数a和b,使得max(a,b) % min(a,b)最大

思路

对于每一个数,就枚举它的倍数,然后每次找第一个比它小的数,更新答案即可

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;

int n, a[5000005], ans, tot, now;

void work(int x)
{
    
    
	for(int j = 1; a[x] * (j - 1) <= a[tot]; ++j)
	{
    
    
		int tt = a[x] * j;
		int p = upper_bound(a + 1, a + tot + 1, tt - 1) - a - 1;
		if(p == 0) continue; 
		int n1 = max(a[x], a[p]);
		int n2 = min(a[x], a[p]); 
		ans = max(ans, n1 % n2);
	}
}

int main()
{
    
    
//	freopen("18.in","r",stdin);
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i)
		scanf("%d", &a[i]);
	if(n == 1) {
    
    
		printf("0");
		return 0;
	}		
	if(n <= 10000) {
    
    
		for(int i = 1; i < n; ++i)
			for(int j = 1; j <= n; ++j)
			{
    
    
				int x = max(a[i], a[j]);
				int y = min(a[i], a[j]);
				ans = max(ans, x - (x / y) * y);
			}
	}
	else {
    
    
		sort(a + 1, a + n + 1);
		tot = unique(a + 1, a + n + 1) - a - 1; 
		now = 1;
		if(tot == 1) {
    
    
			printf("0");
			return 0;
		}
		for(int i = tot; i >= 1; --i)
			work(i);
	}
	printf("%d", ans);
	return 0;
}

Guess you like

Origin blog.csdn.net/LTH060226/article/details/120497518