思路
本题,是个二分答案……
函数部分
我们采用贪心的思想与指针。
从 循环到 ,里面写个 while 循环,若 或者 ,,然后 。
然后判断 是否大于 ,若大于,说明推迟 天也完不成,返回 0。
最后遍历完 ~ ,就返回 1。
bool check(int x)
{
int pos = 1; // 利用指针
int num = x;
for (int i = 1; i <= m; i++)
{
while (pos < a[i] || num == 0)
{
pos++;
num = x;
}
if (pos > a[i] + d)
{
return 0;
}
num--;
}
return 1;
}主函数部分
我们要找最少的机器数,所以 check 成功区是右半区,也就是 r。
AC 代码如下
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n , d , m;
const int N = 1e6 + 5;
int a[N];
bool check(int x)
{
int pos = 1;
int num = x;
for (int i = 1; i <= m; i++)
{
while (pos < a[i] || num == 0)
{
pos++;
num = x;
}
if (pos > a[i] + d)
{
return 0;
}
num--;
}
return 1;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> d >> m;
for (int i = 1; i <= m; i++)
{
cin >> a[i];
}
sort (a + 1 , a + m + 1);
int l = 0 , r = 1e9 + 1;
while (l + 1 < r) // 二分答案模板
{
int mid = (l + r) / 2;
if (check(mid) == 1)
{
r = mid;
}
else
{
l = mid;
}
}
cout << r;
return 0;
}