codeforces 1256D(优先队列+贪心)

时间:2022-07-28
本文章向大家介绍codeforces 1256D(优先队列+贪心),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

You are given a binary string of length n (i. e. a string consisting of n characters ‘0’ and ‘1’).

In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.

Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.

You have to answer q independent test cases.

给定一个二进制字符串,每次可以交换相邻的字符,求经过k次操作后可以获得的最小的字符串

思路

要想尽可能的让二进制字符串小,很容易想到让高位尽可能的与低位的0交换。通过观察,我们发现如果1和0之间全是1的话,就可以直接将1与0交换,交换代价为 a b s ( 1 的 坐 标 − 0 的 坐 标 ) abs(1的坐标-0的坐标) abs(1的坐标−0的坐标),因为数据范围太大,所以可以使用优先队列来进行优化,每次都取靠前的1与靠前的0交换。

AC代码

#include<bits/stdc++.h>
#define x first
#define y second
#define PB push_back
#define mst(x,a) memset(x,a,sizeof(x))
#define all(a) begin(a),end(a)
#define rep(x,l,u) for(ll x=l;x<u;x++)
#define rrep(x,l,u) for(ll x=l;x>=u;x--)
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long ll;
const int N=2*1e5+10;
const int M=1e6+10;
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;
void solve(){
    ll n,k;cin>>n>>k;
    string s;cin>>s;
    priority_queue<int,vector<int>,greater<int>> one,zero;
    bool flag=false;
    rep(i,0,n){
        if(flag){
            if(s[i]=='1') one.push(i);
            else zero.push(i);
        }else{
            if(s[i]=='1'){
                flag=true;
                one.push(i);
            }
        }
    }
    while(one.size() && zero.size()){
        int f1=one.top(),f2=zero.top();
        one.pop();
        //只有在满足交换的条件后,才可以将新的位置push进去,同时这个0也应该pop出去
        if(abs(f1-f2)<=k){
            swap(s[f1],s[f2]);
            k-=abs(f1-f2);
            one.push(f2);
            zero.pop();
        }
    }
    cout<<s<<endl;
}
int main(){
    IOS;
    int t;cin>>t;
    while(t--){
        solve();
    }
    return 0;
}