codeforces 603 div2 Everyone is a Winner(二分)

本文探讨了在处理大规模数据集时,如何利用二分查找算法优化大数除法运算,尤其是在求解特定数学函数的过程中。通过枚举与规律发现,结合二分查找确定解的边界,有效减少了计算复杂度,适用于高精度计算场景。

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

题目大意:

求出\left \lfloor \frac{n}{k} \right \rfloor中,k从1到n的所有解,注意相同的不需要打印。n=1e9.

解题思路:

首先我们可以暴力枚举k打表找找规律。然后我们发现,首先这个函数是单调递减的。同时,因为我们需要输出答案,所以答案数量不会太多。我们考虑这样子做二分,每次我们从x到n做二分。x为相同\left \lfloor \frac{n}{k} \right \rfloor中的最小的k。然后我们找到它的右边界到哪里。

什么意思呢?

若n=108,通过暴力k我们得到如下的\left \lfloor \frac{n}{k} \right \rfloor.

108 54 36 27 21 18 15 13 12 10 9 9 8 7 7 6 6 6 5 5 5 4 4 4 4 4 4 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

第一次x为1,它只有一个数,所以下次x+1作为起点,一直到x=11的位置,对应的\left \lfloor \frac{n}{k} \right \rfloor =9,那么我们通过二分得到下一个起点为13.

#include <bits/stdc++.h>
using namespace std;
int main(){
	int cas;cin>>cas;
	while(cas--){
		int n;cin>>n;
		vector<int> ans;
		int x,y;
		x=1;y=n+1;
		while(x<=n){
			ans.push_back(n/x);
			int val=n/x;
			while(x<y){
				int mid=x+(y-x)/2;
				if(n/mid<val)y=mid;
				else x=mid+1;
			}
			y=n+1;
		}
		ans.push_back(0);
		reverse(ans.begin(),ans.end());
		cout<<ans.size()<<endl;
		for(auto it:ans)cout<<it<<" ";
		cout<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值