Đề bài: http://vn.spoj.com/problems/TJALG/
Thuật toán:
- Bài này thuần sử dụng thuật toánn Tarjan. Thuật toán Tarjan đơn thuần dựa trên thuật toán duyệt đồ thị DFS.
- Các bạn có thể tham khảo thuầ toán Tarjan trong sách của thầy Lê Minh Hoàng
Code:
uses math; const fi='';//spa.inp'; fo='';//spa.out'; maxn=trunc(1e5); maxm=trunc(1e6); oo=trunc(1e9); var i,j,n,m,tpltm,top,tg,count : longint; link,head,ke : array[1..maxm] of longint; low,num : array[1..maxn] of longint; st : array[1..maxm*10] of longint; cx : array[1..maxn] of boolean; procedure add(i,u,v : longint); begin link[i] := head[u]; head[u] := i; ke[i] := v; end; procedure enter; var u,v : longint; begin assign(input,fi);reset(input); readln(n,m); for i:=1 to m do begin read(u,v); add(i,u,v); end; end; function pop : longint; begin pop := st[top]; dec(top); end; procedure push(x : longint); begin inc(top); st[top] := x; end; procedure dfs(u : longint); var i,v : longint; begin inc(count); num[u] := count; low[u] := count; push(u); i := head[u]; while I<>0 do begin v := ke[i]; if cx[v] then if num[v]=0 then begin dfs(v); low[u] := min(low[u],low[v]); end else begin low[u] := min(low[u],num[v]); end; i := link[i]; end; if low[u]=num[u] then begin inc(tpltm); repeat v := pop; cx[v] := false; until v=u; end; end; procedure process; var i : longint; begin fillchar(cx,sizeof(cx),true); for i:=1 to n do if num[i]=0 then begin dfs(i); end; end; procedure print; begin assign(output,fo);rewrite(output); writeln(tpltm); close(output); end; begin enter; process; print; end. |
Recent Comments