MCLONUM - Closest Number

Tác giả: khuc_tuan

Ngôn ngữ: Pascal

// {$APPTYPE CONSOLE}
 {$mode delphi}

var
    a, b : array[0..1000] of char;
    c, d : array['0'..'9'] of integer;
    xong, ok : boolean;
    n, i, j, k : integer;
    cs, ci : char;
    
begin
    readln(a);
    readln(b);
    n := Length(PChar(@a));

    for i:=0 to n-1 do inc(c[b[i]]);

    xong := false;
    begin
        d := c;
        for i:=0 to n-1 do dec(d[a[i]]);
        ok := true;
        for cs := '0' to '9' do if d[cs]<>0 then ok := false;
        if ok then
        begin
            xong := true;
            writeln(a);
        end;
    end;
    if not xong then
    begin
    for i:=n-1 downto 0 do
    begin
        d := c;
        ok := true;
        for j:=0 to i-1 do
        begin
            dec(d[a[j]]);
            if d[a[j]] < 0 then ok := false;
        end;
        if ok then
        begin
            for cs := succ(a[i]) to '9' do
            begin
                if d[cs] > 0 then
                begin
                    for j:=0 to i-1 do write(a[j]);
                    write(cs);
                    dec(d[cs]);
                    for ci := '0' to '9' do
                        for k:=1 to d[ci] do
                            write(ci);
                    writeln;
                    xong := true;
                    break;
                end;
            end;
            if xong then break;
        end;
    end;
    if not xong then
    begin
        writeln(0);
    end;
    end;

    xong := false;
    for i:=n-1 downto 0 do
    begin
        d := c;
        ok := true;
        for j:=0 to i-1 do
        begin
            dec(d[a[j]]);
            if d[a[j]] < 0 then ok := false;
        end;
        if ok then
        begin
            for cs := pred(a[i]) downto '0' do
            begin
                if (cs='0') and (i=0) then continue;
                if d[cs] > 0 then
                begin
                    for j:=0 to i-1 do write(a[j]);
                    write(cs);
                    dec(d[cs]);
                    for ci := '9' downto '0' do
                        for k:=1 to d[ci] do
                            write(ci);
                    writeln;
                    xong := true;
                    break;
                end;
            end;
            if xong then break;
        end;
    end;
    if not xong then
    begin
        writeln(0);
    end;
end.

Download