Atcoder Beginner Contest 341D Only one of two

文章描述了如何利用数学中的包括排除原理和二分查找算法,计算给定两个数n和m下,小于某个x且仅能被n或m整除的第k个最大的整数。通过计算x除以n和m的结果以及它们的最小公倍数,得出符合条件的整数数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

problem link

Its is evident that the data is too large for enumeration. However, for a given x x x, we can easily calculate the number of positive integers less than x x x that is divisible by only one of n , m n,m n,m.

Using the inclusion-exclusion principle, we can subtract the number of integers that are divisible by both x x x and y y y from entire set of x , y x,y x,y multiples. More formally, the number of integers that fits the requirement is ⌊ x n ⌋ + ⌊ x m ⌋ − 2 ⋅ ⌊ x l c m ( n , m ) ⌋ \lfloor \frac{x}{n} \rfloor + \lfloor \frac{x}{m} \rfloor-2\cdot\lfloor\frac{x}{lcm(n,m)}\rfloor nx+mx2lcm(n,m)x, where l c m ( n , m ) lcm(n,m) lcm(n,m) denotes the least common multiple of n n n and m m m.

With this in mind, we can use binary search to calculate the k k kth largest integer that satisfies the requirement.

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
using namespace std;
// const long long Maxn=510;
// const long long dx[]={1,-1,0,0},dy[]={0,0,-1,1};
long long n,m,k,lcm;
inline long long read()
{
	long long s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
	return s*w;
}
long long gcd(long long x,long long y)
{
	if(y==0)return x;
	return gcd(y,x%y);
}
int main()
{
	// freopen("in.txt","r",stdin);
	n=read(),m=read(),k=read();
	lcm=n*m/gcd(n,m);
	long long l=1,r=(1ll<<60);
	while(l<r)
	{
		long long x=(l+r)>>1;
		long long tot=x/n+x/m-2ll*(x/lcm);
		if(tot>=k)r=x;
		else l=x+1;
	}
	cout<<l<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值