SA模板

sa模板(pascal倍增)

for i:=1 to n do
    begin
        s[i]:=t[i];x[i]:=ord(s[i]);
        if x[i]>max then max:=x[i];
        inc(ws[x[i]]);
    end;
    for i:=1 to max do inc(ws[i],ws[i-1]);
    for i:=n downto 1 do
    begin
        sa[ws[x[i]]]:=i;dec(ws[x[i]]);
    end;
    j:=1;
    while j<=n do
    begin
        k:=0;max:=0;fillchar(ws,sizeof(ws),0);
        for i:=n-j+1 to n do
        begin
            inc(k);y[k]:=i;inc(ws[x[y[k]]]);
            if x[y[k]]>max then max:=x[y[k]];
        end;
        for i:=1 to n do
            if sa[i]>j then
            begin
                inc(k);y[k]:=sa[i]-j;inc(ws[x[y[k]]]);
                if x[y[k]]>max then max:=x[y[k]];
            end;
        for i:=1 to max do inc(ws[i],ws[i-1]);
        for i:=n downto 1 do
        begin
            sa[ws[x[y[i]]]]:=y[i];dec(ws[x[y[i]]]);
        end;
        for i:=1 to n do
        begin
            y[i]:=x[i];x[i]:=0;
        end;
        k:=1;x[sa[1]]:=1;
        for i:=2 to n do
        begin
            if (y[sa[i-1]]<>y[sa[i]]) or (y[sa[i-1]+j]<>y[sa[i]+j]) then inc(k);
            x[sa[i]]:=k;
        end;
        if k=n then break;j:=j*2;
    end;
    for i:=1 to n do rank[sa[i]]:=i;
    k:=0;
    for i:=1 to n do
    begin
        if k>0 then dec(k);
        j:=sa[rank[i]-1];
        while (i+k<=n) and (j+k<=n) and (s[i+k]=s[j+k]) do inc(k);
        height[rank[i]]:=k;if k>r then r:=k;
    end;

你可能感兴趣的:(模板,后缀数组,SA)