Problem Description
给你n个用户,和k-1个管道转换器,分别1转换为2,3,……k;
问你至少需要多少个转换器就可以满足用户需求
Input
4 3
5 5
8 4
Output
2
1
-1
代码:
#include<iostream>
using namespace std;
long long n, k;
//sum = 1 + 2 - 1 + 3 - 1 …… + k - 1 = 1 + 1 + 2 + 3 + …… + k - 1;
int judge(long long n1)
{
long long b = k - n1;
long long sum = (b + k - 1) * n1 / 2 + 1;//等差数列求和 + 1
return sum >= n;//代表能满足用户
}
int search()
{
if(!judge(k - 1)) return -1;//不满足
if(judge(0)) return 0;//满足
int i = 0, j = k - 1;//i是不满足,j是满足
while(i < j)
{
int mid = (i + j) / 2;
if(judge(mid)) j = mid;//满足 缩小需要的管道数
else i = mid;
if(i == j - 1) return j;
}
}
int main()
{
while(cin >> n >> k) {
cout << search() << endl;
}
return 0;
}