UVa 10170 - The Hotel with Infinite Rooms

本文详细阐述了如何通过数学方法求解从s开始的递增序列加和不小于D的最后加数的问题,并利用二分查找算法优化求解过程。文章深入分析了解题思路和算法实现,提供了具体的代码示例。

题目:求从s开始的递增序列(每次加1),求出他们加和不小于D的那个最后的加数。

分析:数学题,分治。s + s+1 + ... + n = n*(n+1)/2 - s*(s-1)/2 = (n+s)*(n-s+1)/2。

             直接二分答案即可(二分范围0~10^8)。

说明:(⊙_⊙)。

#include <iostream>
#include <cstdlib> 

using namespace std;

long long sum(long long s, long long n)
{
	return (n-s+1LL)*(n+s)/2LL;
}

long long bs(int S, long long D)
{
	long long mid,l = 1LL,r = 100000000LL;
	while (l < r) {
		mid = l+(r-l)/2LL;
		if (sum(S, mid) >= D)
            r = mid;  
        else l = mid+1LL;  
	} 
	return r;
}

int main()
{
	long long s,D;
	while (cin >> s >> D)
		cout << bs(s, D) << endl;
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值