最优交换

Description
这里写图片描述

Input
这里写图片描述

Output
这里写图片描述

Sample Input

2
1432 2
4321 2

Sample Output

4312
4321
这里写图片描述

Data Constraint
这里写图片描述
.
.
.
.
.
.
.
.

分析

这里写图片描述
.
.
.
.
.
.
.
.
.

程序:
var
t,i,j,k,h,r,l,max:longint;
n:char;
s,zfc:string;
begin
    assign(input,'swap.in');
    reset(input);
    assign(output,'swap.out');
    rewrite(output);
    readln(t);
    for r:=1 to t do
    begin
        readln(zfc);
        val(copy(zfc,pos(' ',zfc)+1,length(zfc)-pos(' ',zfc)),k,j);
        delete(zfc,pos(' ',zfc),length(zfc)-pos(' ',zfc)+1);
        l:=length(zfc);
        s:=zfc;
        for i:=1 to l do
        begin
            if k=0 then break;
            max:=0;h:=0;
            for j:=i+1 to l do
            if (ord(s[j])-ord('0')>max)and(i+k>=j) then
            begin
                max:=ord(s[j])-ord('0');
                h:=j;
            end;
            if (max>ord(s[i])-ord('0')) then
            begin
                n:=s[h];
                for j:=h-1 downto i do
                begin
                    s[j+1]:=s[j];
                    dec(k);
                end;
                s[i]:=n;
            end;
        end;
        writeln(s);
    end;
    close(input);
    close(output);
end.

原文地址:https://www.cnblogs.com/YYC-0304/p/9499997.html