麻烦各位dalao来看看吧,我代码里有解释的QAQ
var
bi:boolean;
t,a1,a2,num,tot,head,tail:longint;
s1,s2,s3:char;
i,j,m,n,k,p:longint;
map:array[0..30,0..30]of boolean;
ru,s:array[0..30]of longint;
f:array[0..300]of longint;
begin
readln(n,m);
bi:=false;
while m<>0 do
begin
dec(m); inc(t);//记录这是第几个关系
readln(s1,s2,s3);
a1:=ord(s1)-64; a2:=ord(s3)-64;
map[a1,a2]:=true;//邻接矩阵存图
inc(ru[a2]);//记录每个点的入度
head:=0; tail:=0; tot:=0; num:=0;
for i:=1 to n do
if ru[i]=0 then
begin
inc(tail); f[tail]:=i;
inc(tot); inc(num);
{tot记的是访问了几个点
num记的是有几个入度为0的点,如果有多个就还没确定数列对吧}
end;
for i:=1 to n do s[i]:=ru[i];//拓扑的临时数组
while head<tail do
begin
inc(head);
for i:=1 to n do
if map[f[head],i]=true then
begin
dec(s[i]);
if s[i]=0 then
begin
inc(tail); f[tail]:=i; inc(tot);
end;
end;
end;
if tot<n then//如果不是所有点都被访问了,就说明有环对吧
begin
writeln('Inconsistency found after ',t,' relations.');
exit;
end;
if (tot=n)and(num=1) then
begin
write('Sorted sequence determined after ',t,' relations: ');
for i:=1 to tail do write(chr(f[i]+64));
writeln;
exit;
end;
end;
writeln('Sorted sequence cannot be determined.');
end.