分析完题目后,容易想到贪心,每次合并两个中间 的数量最小的“ 1 块”,而每次合并肯定会减少一个“ 1 块”。正确性显然。
步骤:
· 先遍历一遍 ,在这个过程中统计有多少个“ 1 块”,保存进 ;还要统计有多少个之间隔了 个 的“ 1 块”,把这个数量保存进 。
· 从 到 遍历 数组,如果能合并就合并, 。
最后献上我码风独特的代码:
#include <iostream>
#include <queue>
using namespace std;
const int N=1e7+3;
int n,k,cnt[N];
char s[N];
int main()
{
scanf("%d%d%s",&n,&k,s+1);
int lst=-1,ans=0;
for (int i=1;i<=n;++i)
{
if (s[i]=='1')
{
if (lst<i-1)
{
++ans;
if (lst!=-1) ++cnt[i-lst-1];
}
lst=i;
}
}
for (int i=1;i<=1e7;++i)
{
while (k>=i && cnt[i])
k-=i,--ans,--cnt[i];
}
printf("%d",ans);
return 0;
}