Codeforces-1256-D. Binary String Minimizing(贪心)
Input
3 8 5 11011010 7 9 1111100 7 11 1111100
Output
01011110 0101111 0011111
题意:t组样例,给一个长度为n的字符串,要求在k步以内进行字符交换(1步只能交换i和i+1)使得字符串字典序最小。
思路:贪心,存下0的位置,让前面的0尽可能往前移,然后就是模拟计算操作。
#pragma comment(linker, "/STACK:1024000000,1024000000") #pragma GCC optimize(2) #include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<queue> #include<set> #include<cmath> #include<string> #include<map> #include<vector> #include<ctime> using namespace std; #define mm(a,b) memset(a,b,sizeof(a)) typedef long long ll; const int maxn = 1e6+10;; const int inf = 0x3f3f3f3f; const int mod = 1e9+7; int gcd(int a,int b) {if(b==0) return a;return gcd(b,a%b);} char s[maxn]; int main(){ int q; scanf("%d",&q); while(q--) { vector<int>v; int n; ll k; scanf("%d %lld",&n,&k); scanf("%s",s); for(int i=0;i<n;i++) { if(s[i]=='0') v.push_back(i); } int len=v.size(); if(v.size()==n||v.size()==0) { printf("%s\n",s); continue; } int pos1=0,pos2=0; while(k>0&&pos2<len&&pos1<=n-1) { if(s[pos1]=='0') { pos1++; } else if(v[pos2]<=pos1) { pos2++; } else { int cnt=v[pos2]-pos1; if(k<cnt) { pos1=v[pos2]-k; k=0; } else k=k-(cnt); s[pos1]='0'; s[v[pos2]]='1'; pos1++; pos2++; } } printf("%s\n",s); } return 0; } /* 9 8 1 11011010 8 2 11011010 8 3 11011010 8 4 11011010 8 5 11011010 8 6 11011010 8 7 11011010 8 10 11011010 8 50 11011010 */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端