糖果促销。

小度最喜欢吃糖啦!!!
这天商店糖果促销,可给小度高兴坏了。

促销规则:一颗糖果有一张糖纸,�p 张糖纸可以换取一颗糖果。换出来糖果的包装纸当然也能再换糖果。

小度想吃 �k 颗糖果,他需要买多少颗糖?

格式

输入格式:

第一行一个整数 �(1≤�≤106)T(1≤T≤106) ,表示测试数据组数;
接下来�T行,每行两个整数 ��,��(1≤��≤109,0≤��≤109)pi​,ki​(1≤pi​≤109,0≤ki​≤109) ,表示第 �i 次测试中, ��pi​ 张糖纸换一颗糖,小度想吃 ��ki​ 颗糖。

输出格式:

�T 行,每行一个整数表示需要买多少颗糖果。

样例 1

输入:

3
3 4
4 5
2 7

复制

输出:

3
4
4

哪位大佬告诉我这为什么就能得出正确答案啊,我用二分为什么超时?

ac代码

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<vector>
#include<math.h>
#include<iomanip>
#include<set>
#include<queue>
#include<stack> 
#include<map>
using namespace std;
int t, k, n;
int main()
{
	cin >> t;
	for (int i = 0; i < t; i++)
	{
		cin >> k >> n;
		if (n == 0)
			cout << 0 << endl;
		else
		{
			n = n - (n - 1) / k;
			cout << n << endl;
		}
	}
}

二分代码(超时)

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<vector>
#include<math.h>
#include<iomanip>
#include<set>
#include<queue>
#include<stack> 
#include<map>
using namespace std;
int t, k, n,ans=0,l,r,mid;
int fun(int x);
int check(int x)
{
	if (fun(x) + x < n)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
int fun(int x)
{
	if (x / k > 0)
	{
		ans = ans + x / k;
		if (x % k > 0)
			fun(x % k + x / k);
		else
			fun(x / k);
	}
	return ans;
}
int main()
{
	cin >> t;
	for (int i = 0; i < t; i++)
	{
		cin >> k >> n;
		if (k == 1)
		{
			cout << 1 << endl;
			continue;
		}
		if (n == 0)
		{
			cout << 0 << endl;
			continue;
		}
		l = 0, r = 100000;
		while (l < r)
		{
			mid = (l + r) / 2;
			ans = 0;
			if (check(mid) == 1)
			{
				l = l + 1;
			}
			else 
			{
				r = mid;
			}
		}
		cout << l << endl;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值