拓扑排序

http://unbelievable.ycool.com/post.743864.html
top sort..... o(m)...

一直... 偶都只会 O(N^2)的 ....
07-01... 有一题..用到了 O(M) 的  top sort  + 指针....

这偶就 卡住了....

今天晚上.... 写了个程序(8过...借鉴了ZC 的...... )

program topsort;
const inf='input.txt';
     ouf='output.txt';
     maxn=100;
type pnode=^graph;
    graph=record
            p:longint;
            next:pnode;
          end;
var g:array [1..maxn] of pnode;
   id,st:array [1..maxn] of longint;
   n:longint;

procedure add(x:longint;var t:pnode);
var tmp:pnode;
begin
 new(tmp);
 tmp^.p:=x;
 tmp^.next:=t;
 t:=tmp;
end;

procedure init;
var i,x,t:longint;
begin
 assign(input,inf);reset(input);
 readln(n);
 for i:=1 to n-1 do begin
   read(x);
   while x>0 do begin
     dec(x);
     read(t); inc(id[t]);
     add(t,g[I]);
   end;
   readln;
 end;
 close(input);
end;

procedure tsort;
var h,t:longint;
   tmp:pnode;
begin
 for h:=1 to n do
   if id[h]=0 then begin st[1]:=h; break end;
 h:=0; t:=1;
 repeat
   inc(h);
   tmp:=g[h];
   while tmp<>nil do begin
     dec(id[tmp^.p]);
     if id[tmp^.p]=0 then begin
       inc(t); st[t]:=tmp^.p;
     end;
     tmp:=tmp^.next;
   end;
 until h=t;
end;

procedure out;
var i:longint;
begin
 assign(output,ouf);rewrite(output);
 for i:=1 to n do
   writeln(st[I]);
 close(output);
end;

begin
 init;
 tsort;
 out;
end.

posted @ 2008-12-05 15:31  jesonpeng  阅读(141)  评论(0)    收藏  举报