NOIP2015信息传递

Tarjan求最小强连通分量(注意要形成一个环而不是一个点,即size>1).

Pascal:

var
        n,x,l,time,top,t,minn:longint;
        i                    :longint;
        dfn,low,z,size       :array[0..200010] of longint;
        last,pre,other       :array[0..200010] of longint;
        vis                  :array[0..200010] of boolean;
function min(a,b:longint):longint;
begin
   if a0) do
   begin
      p:=other[q];
      if (dfn[p]=0) then
      begin
         dfs(p);
         low[x]:=min(low[x],low[p]);
      end else
      if vis[p] then low[x]:=min(low[x],dfn[p]);
      q:=pre[q];
   end;
   //
   if (dfn[x]=low[x]) then
   begin
      cur:=-1;inc(t);
      while (cur<>x) do
      begin
         cur:=z[top];
         dec(top);
         vis[cur]:=false;
         inc(size[t]);
      end;
   end;
end;

begin
   read(n);
   for i:=1 to n do
   begin
      read(x);
      connect(i,x);
   end;
   //
   for i:=1 to n do if (dfn[i]=0) then dfs(i);
   minn:=maxlongint;
   for i:=1 to t do
    if (size[i]1) then minn:=size[i];
   writeln(minn);
end.

C:

#include
#define maxn 200010

int l = 0;
int time = 0, top = 0;
int last[maxn], other[maxn], pre[maxn];
int dfn[maxn], low[maxn], belong[maxn], size[maxn];
int z[maxn], vis[maxn];

int min(int x, int y) {
    return((x) < (y) ? x : y);
}

void connect(int x, int y){
    l++;
    pre[l] = last[x];
    last[x] = l;
    other[l] = y;
}

void dfs(int x){
    int p, q;
    int cur;

    time++;
    dfn[x] = time;
    low[x] = time;
    vis[x] = 1;
    top++;
    z[top] = x;
    //
    q = last[x];
    while (q != 0) {
        p = other[q];
        if (dfn[p] == 0){
            dfs(p);
            low[x] = min(low[x], low[p]);
        } else if (vis[p] == 1) low[x] = min(low[x], dfn[p]);
        q = pre[q];
    }
    //
    if (dfn[x] == low[x]) {
        cur = -1;
        while (cur != x){
            cur = z[top];
            belong[cur] = x;
            vis[cur] = 0;
            size[belong[cur]]++;
            top--;
        }
    }
}

int main(){
    int i;
    int n , x;
    int ans = maxn;

    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        scanf("%d", &x);
        connect(i, x);
    }
    for (i = 1; i <= n; i++)
        if (dfn[i] == 0) dfs(i);
    for (i = 1; i <= n; i++) 
        if (size[belong[i]] > 1) ans = min(ans, size[belong[i]]);
    printf("%d\n", ans);
    return 0;
}

——by Eirlys
转载请注明出处=w=

 

NOIP2015信息传递_第1张图片

你可能感兴趣的:(noip复赛=A=,tarjan)