TYVJ 1161 [聚会的名单]--Trie树

今天下午有位童鞋写这个题用暴力得了50分,感觉十分不爽,于是过来找Kudo求救……碰巧旁边的JAF DTing……

于是他现学现卖,写了一个Trie树来解决~

[pascal 代码]

TYPE
        LZY=RECORD
                GOT:LONGINT;
                NEXT:ARRAY['a'..'z'] OF LONGINT;
        END;
VAR
        T:ARRAY[1..1000000]OF LZY;
        S:STRING;
        N,M,I,TN,J,NOW:LONGINT;
PROCEDURE GETINTREE(S:STRING);
 VAR
        I,NOW:LONGINT;
 BEGIN
        NOW:=1;
        FOR I:=1 TO LENGTH(S) DO
        IF T[NOW].NEXT[S[I]]<>0 THEN NOW:=T[NOW].NEXT[S[I]] ELSE
                BEGIN
                        INC(TN);
                        T[TN].GOT:=0;
                        FILLCHAR(T[TN].NEXT,SIZEOF(T[TN].NEXT),0);
                        T[NOW].NEXT[S[I]]:=TN;
                        NOW:=TN;
                END;
        INC(T[NOW].GOT);
 END;
FUNCTION CHECK(S:STRING):LONGINT;
 VAR
        I,NOW:LONGINT;
 BEGIN
        NOW:=1;
        FOR I:=1 TO LENGTH(S) DO
        IF T[NOW].NEXT[S[I]]<>0 THEN NOW:=T[NOW].NEXT[S[I]] ELSE EXIT(0);
        EXIT(T[NOW].GOT);
 END;
BEGIN
        TN:=1;
        T[1].GOT:=0;
        FILLCHAR(T[1].NEXT,SIZEOF(T[1].NEXT),0);
        READLN(N);
        FOR I:=1 TO N DO
                BEGIN
                        READLN(S);
                        GETINTREE(S);
                END;
        READLN(M);
        FOR I:=1 TO M DO
                BEGIN
                        READLN(S);
                        WRITELN(CHECK(S));
                END;
END.
posted @ 2011-10-28 19:10  NoRush  阅读(202)  评论(0编辑  收藏  举报