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;
}
本文作者:风归去
本文链接:https://www.cnblogs.com/N-lim/p/16906991.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步