nyoj1057 寻找最大数(三)

本文介绍了一种通过限定步数内操作来最大化字符串数值的方法。通过从高位到低位寻找最大可用字符并进行替换,最终得到在规定操作次数内的最大可能字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题: http://acm.nyist.net/JudgeOnline/problem.php?pid=1057

//思路都在代码中
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string> 
using namespace std;
int main()
{
	//从高位到低位,为他找可寻找范围内(受k限制)最大的那个数 
	char st[51];
	int k;
	while(~scanf("%s %d",st,&k))
	{
		string str(st);
		int len=str.length();
		int now=0;
		while(k>0 && now<len) //遍历字符串,从高位到低位(左到右) 
		{
			int pos=now;
			char ch=str[now];
			int end=min(len,now+k+1);//可寻找范围 
			for(int i=now+1;i<end;i++) //找范围内最大的字母,移动过程即 删除插入过程。 
			{
				if(ch<str[i])
				{
					pos=i;
					ch=str[i];
				}
			}
			if(pos!=now) 
			{
				k=k-(pos-now);
				string t(str.c_str()+pos,str.c_str()+pos+1);//把那个数字符串化 
				str.erase(pos,1);//删掉那个数
		 		str.insert(now,t);//插入
			}
			now++;
		}
		printf("%s\n",str.c_str()); 
	}
	return 0;
}         


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值