@x=sort{(split/ /,$a)[2]<=>(split/ /,$b)[2]}<>;$y{a}=1;X:{do{/(.) (\w+)/;$1 ne'T'and$y{$1}&&!$y{$2}++||$y{$2}&&!$y{$1}++and$_="T $_",redo X}for@x}chomp,/T/ ||($_="F $_"),print"$_\x0d
"for@x
Note that non-ascii characters in the above source code will be escaped (such as \x9f).