原题: 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; }