program perm; var t: text; a: array [0..9] of longint; m, n, s: ansistring; i, d, len_final, i2: longint; top: boolean; procedure try(k: longint); var i, b: longint; begin if k>len_final then begin while s[1]='0' do delete(s, 1, 1); if s=m then exit(); writeln(t, s); close(t); halt(); end; if top then b:=ord(m[k])-48 else b:=9; for i:=b downto 0 do begin if a[i]>0 then begin s[k]:=chr(i+48); dec(a[i]); if top then top:=(i=ord(m[k])-48); try(k+1); inc(a[i]); end; end; end; begin top:=true; assign(t, 'PERM.INP'); reset(t); readln(t, n); readln(t, m); close(t); for i:=1 to length(n) do begin inc(a[ord(n[i])-48]); inc(d); end; assign(t, 'PERM.OUT'); rewrite(t); if length(n)>length(m) then begin if d-a[0]>length(m) then begin write(t, -1); close(t); exit(); end; a[0]:=length(m)-(d-a[0]); end; if length(n)>=length(m) then begin len_final:=length(m); s:=m; try(1); end else begin for i:=9 downto 0 do for i2:=1 to a[i] do write(t, i); close(t); halt(); end; write(t, -1); close(t); end.
Comments