C. Sum of Substrings题解

C. Sum of Substrings

题目大概意思,给你一个01串,求和最小,其中和是该串所有相邻字符所组成的十进制数的和。
如:0110, sum = 01 + 11 + 10 = 22。
通过观察我们可以发现,除了第一个位置和最后一个位置,其他位置上的1对和的贡献都是11。
所以我们只需要特殊考虑挪1到第一个和最后一个位置上。
题目没说必须挪,所以我们可以不用挪。
另外,注意只有一个1的情况!

#include<bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;
int t, n, k;
char st[N];

signed main(){
    cin >> t;
    while(t --){
        cin >> n >> k;
        memset(st, 0, sizeof st);
        cin >> st;
        int pos1 = 0, pos2 = 0;
        int cnt = 0;
        bool flag = false;
        for(int i = 0; i < strlen(st); i++){
            if(pos1 == 0 && st[i] == '1' && flag == false){
                pos1 = i;
                flag = true;
            } 
            if(st[i] == '1') cnt ++;
        }
        for(int i = n - 1; i >= 0; i--){
            if(pos2 == 0 && st[i] == '1'){
                pos2 = i;
                break;
            }
        }
        if(cnt == 0){
            cout << 0 << endl;
            continue;
        }
        if(k == 0){
            int res = 0;
            if(st[0] == '1') res = 10, cnt --;
            if(st[n - 1] == '1') res += 1, cnt --;
            cout << res + cnt * 11 << endl;
            continue;
        }
        if(cnt == 1){
            if(k >= n - pos2 - 1){
                cout << 1 << endl;
            }
            else if(k >= pos1){
                cout << 10 << endl;
            }
            else cout << 11 << endl;
            continue;
        }
            int ans = 0;
            if(pos2 == n - 1){
                ans = 1;
                cnt --;
            }
            else{
                if(k >= n - pos2 - 1){
                    k -= n - pos2 - 1;
                    ans += 1;
                    cnt --;
                }
            }
            if(pos1 == 0){
                ans += 10;
                cnt --;
            }
            else{
                if(k >= pos1){
                    ans += 10;
                    cnt --;
                }
            }
            cout << ans + 11 * cnt << endl;
    }
    return 0;
}
posted @ 2022-11-19 20:35  风归去  阅读(49)  评论(0编辑  收藏  举报