跳到正文

题解

P12350 光影 题解

c_legg约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
获赞
1
题目
P12350

版本

  1. v1当前

思路

考虑贪心。

很显然的是:设 ϕ\phi 为 …10…0undefined1…\texttt{\dots 1}\overlinesegment{\texttt{0\dots 0}}\texttt{1\dots} 中用线段标注出的一段,则把 ϕ\phi 删除后,用 1\texttt{1} 连成的块的数量会减一。

更显然的是:如果同时有 ϕ1\phi_1 和 ϕ2\phi_2,且 ∣ϕ1∣<∣ϕ2∣\mid\phi_1\mid\lt\mid\phi_2\mid,则删除 ϕ1\phi_1 比删除 ϕ2\phi_2 更优。

那我们可以每次删除最短的 ϕ\phi 并更新 ans\text{ans} 与 kk 直到 kk “用光”。

使用优先队列存储 ∣ϕ∣\mid\phi\mid,注意特判全 0\texttt{0} 即可。

代码

C++
#include <bits/stdc++.h>
typedef long long ll;
#define one(x) ((ll)(1e##x))
using namespace std;
typedef pair<int, int> pii;

int n, k;

string s;

int las(-2);

priority_queue<int, vector<int>, greater<int> > dis;

int ans;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin>>n>>k>>s;
    for(int i(0); i<n; i++) {
        if(s[i]=='1') {
            if(las>=0 && las!=i-1) dis.push(i-las-1);
            las=i;
        }
    }
    if(dis.empty() && s.find("1")==string::npos) {
        cout<<0<<"\n";
        return 0;
    }
    ans=dis.size()+1;
    while(dis.size()) {
        k-=dis.top();
        dis.pop();
        if(k<0) break;
        ans--;
    }
    cout<<ans;
    return 0;
}
原文