思路:先求符和条件的每个间隔的代价,想要获得最多次切割,贪心一下即可(按照代价从小到大依次切割)
注意代价是两边的差值取绝对值
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int n, b;
scanf("%d%d", &n, &b);
int arr[1010] = {0}, cost[1010] = {0};
for(int i = 1; i <= n; i++)
{
scanf("%d", &arr[i]);
cost[i] = 0;
}
int odd, even, cnt;
odd = even = cnt = 0;
for(int i = 1; i < n; i++)
{
if(arr[i] % 2 == 0)
even++;
else
odd++;
if(odd == even)
{
cost[cnt++] = abs(arr[i + 1] - arr[i]);
}
}
sort(cost, cost + cnt);
int tot = 0;
for(int i = 0; i < cnt; i++)
{
if(b >= cost[i])
{
b -= cost[i];
tot++;
}
else
{
printf("%d\n", tot);
return 0;
}
}
printf("%d\n", tot);
return 0;
}
题目来源:https://codeforces.com/contest/998/problem/B