P2678 [NOIP2015 提高组] 跳石头
https://www.luogu.com.cn/problem/P2678
本题使用二分+贪心的方法来解决。首先是二分的模板:
while (l <= r)
{
int mid = l + r >> 1;
if (check(mid) == true)
{
ans = mid;
l = mid + 1;
}
else
{
r = mid - 1;
}
}
然后再通过贪心,求出搬走石头的个数并于m的值进行比较,判断当前mid值是不是符合题意。
bool check(int mi)
{
int now = 0, num = 0;
for (int i = 1; i <= n; i++)
{
if (a[i] - now < mi)
{
num++;
}
else
{
now = a[i];
}
}
if (num > m)return false;
else return true;
}
完善代码
#include<bits/stdc++.h>
using namespace std;
#define TLE ios::sync_with_stdio(false)
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int L,n, m;
int a[N];
int ans;
bool check(int mi)
{
int now = 0, num = 0;
for (int i = 1; i <= n; i++)
{
if (a[i] - now < mi)
{
num++;
}
else
{
now = a[i];
}
}
if (num > m)return false;
else return true;
}
int main()
{
TLE;
cin >> L >> n >> m;
a[0] = 0;
for (int i = 1; i <= n; i++)
cin >> a[i];
a[++n] = L;
int l = 0, r = INF;
while (l <= r)
{
int mid = l + r >> 1;
if (check(mid) == true)
{
ans = mid;
l = mid + 1;
}
else
{
r = mid - 1;
}
}
cout << ans << endl;
return 0;
}
P1182 数列分段 Section II 题解https://www.luogu.com.cn/problem/P1182
本题思路与上题相似,check函数如下
bool check(int mi)
{
int tot = 0, num = 0;
for (int i = 1; i <= n; i++)
{
if (tot + a[i] <= mi)tot += a[i];
else num++,tot = a[i];
}
if (num >= m)return false;
else return true;
}
完善代码
#include<bits/stdc++.h>
using namespace std;
#define TLE ios::sync_with_stdio(false)
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int L, n, m;
int a[N];
int ans;
bool check(int mi)
{
int tot = 0, num = 0;
for (int i = 1; i <= n; i++)
{
if (tot + a[i] <= mi)tot += a[i];
else num++,tot = a[i];
}
if (num >= m)return false;
else return true;
}
int main()
{
TLE;
int l = 0, r = 0;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
l = max(l, a[i]);
r += a[i];
}
while (l <= r)
{
int mid = l + r >> 1;
if (check(mid))
{
ans = mid;
r = mid - 1;//本题找最小,所以二分写法与上题不同
}
else
{
l = mid + 1;
}
}
cout << ans << endl;
return 0;
}