program DIPLOMAT; {$APPTYPE CONSOLE} type TCharSet=set of char; PDiplomat=^TDiplomat; TDiplomat=record Country:Word; Langs:TCharSet; Supports:array[0..21] of Word; end; TDiplomats=array[0..21]of TDiplomat; function ReadCountry:Word; var S:String[3]; begin Read(S); Result:=(Ord(S[1])-Ord('A')+1)+27*(Ord(S[2])-Ord('A')+1)+27*27*(Ord(S[3])-Ord('A')+1) end; procedure WriteCountry(ACountry:Word); var a,b,c:byte; s:string[3]; begin a:=ACountry div (27*27); Dec(ACountry,a*27*27); b:=ACountry div 27; Dec(ACountry,b*27); c:=ACountry; Write(Chr(c+Ord('A')-1),Chr(b+Ord('A')-1),Chr(a+Ord('A')-1)) end; function ReadCharSet:TCharSet; var C:Char; begin Read(C); Result:=[]; while C in ['A'..'Z'] do begin Include(Result,C); Read(C) end; end; procedure WriteCharSet1(CS:TCharSet); var c:char; begin for c:='A' to 'Z' do begin if c in CS then BEGIN Write(c); Exit END; end; end; function ReadDiplomat:TDiplomat; var C:Char; begin with Result do begin Country:=ReadCountry; Read(C); Langs:=ReadCharSet; C:=' '; Supports[0]:=1; while C=' ' do begin Supports[Supports[0]]:=ReadCountry; Inc(Supports[0]); Read(C) end; Dec(Supports[0]); Read(C) end end; var d:TDiplomats; function GetDiplomat(ACountry:Word):PDiplomat; var i:integer; begin for i:=1 to d[0].Country do if d[i].Country=ACountry then begin Result:=@d[i]; Exit end; Result:=nil; End; function CanSit(const D1,D2:TDiplomat):Boolean; var i:integer; begin Result:=D1.Langs*D2.Langs<>[]; if not Result then Exit; { for i:=1 to D1.Supports[0] do if D1.Supports[i]=D2.Country then begin Result:=True; Break end; if not Result then Exit; } for i:=1 to D2.Supports[0] do if D2.Supports[i]=D1.Country then begin Result:=True; Break end; end; var List:TDiplomats; OK:Boolean; procedure Search; var i,j:integer;done:boolean; begin if List[0].Country=d[0].Country then begin OK:=CanSit(List[0],List[List[0].Country]); Exit end; Inc(List[0].Country); for i:=1 to List[List[0].Country-1].Supports[0] do begin List[List[0].Country]:=GetDiplomat(List[List[0].Country-1].Supports[i])^; done:=false; for j:=1 to List[0].Country-1 do if List[j].Country=List[List[0].Country].Country then begin done:=true; break end; if done then continue; if CanSit(List[List[0].Country-1],List[List[0].Country]) then Search; if OK then Break end; Dec(List[0].Country) end; var i,n:integer; begin assign(input,'diplomat.dat');reset(input); assign(output,'diplomat.sol');rewrite(output); readln(n); d[0].Country:=n; for i:=1 to n do d[i]:=ReadDiplomat; List[0].Country:=1; List[1]:=d[1]; OK:=False; Search; if not OK then Writeln('NO SOLUTION EXIST') else begin List[n+1]:=List[1]; List[0]:=List[n]; for i:=1 to n do begin WriteCharSet1(List[i-1].Langs*List[i].Langs); Write(' '); WriteCountry(List[i].Country); Write(' '); WriteCharSet1(List[i].Langs*List[i+1].Langs); Writeln end; end; close(input);close(output) end.