Cod sursa(job #1236332)

Utilizator andreiiiiPopa Andrei andreiiii Data 1 octombrie 2014 19:58:49
Problema Trie Scor 45
Compilator java Status done
Runda Arhiva educationala Marime 2.81 kb
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws IOException{
	    Scanner in = new Scanner(new FileInputStream("trie.in"));
        //InputReader in = new InputReader(System.in);
        PrintWriter out = new PrintWriter("trie.out");
        //PrintWriter out = new PrintWriter(System.out);

        Trie T = new Trie();

        int op;
        while (in.hasNext()) {
            op = in.nextInt();
            String S = in.next();

            if (op == 0)
                T.insert(S);
            else if (op == 1)
                T.erase(S);
            else if (op == 2)
                out.println(T.count(S));
            else
                out.println(T.prefix(S));
        }

        out.close();
    }

    private static class Trie {
        private class Node {
            int cnt, nr;
            Node[] links;

            Node() {
                links = new Node[26];
                cnt = nr = 0;
            }
        }

        private Node root;

        Trie() {
            root = new Node();
        }

        public void insert(String S) {
            Node p = root;
            for (int i = 0; i < S.length(); ++i) {
                int x = S.charAt(i) - 'a';

                if (p.links[x] == null) {
                    p.links[x] = new Node();
                    p.nr++;
                }

                p = p.links[x];
            }

            p.cnt++;
        }

        private void Erase(Node node, String S, int pos) {
            if (pos == S.length()) {
                node.cnt--;
            } else {
                int x = S.charAt(pos) - 'a';

                Erase(node.links[x], S, pos + 1);
                if (node.links[x].cnt == 0 && node.links[x].nr == 0) {
                    node.links[x] = null;
                    node.nr--;
                }
            }
        }

        public void erase(String S) {
            Erase(root, S, 0);
        }

        public int count(String S) {
            Node p = root;
            for (int i = 0; i < S.length(); ++i) {
                int x = S.charAt(i) - 'a';

                if (p.links[x] == null)
                    return 0;

                p = p.links[x];
            }

            return p.cnt;
        }

        public int prefix(String S) {
            Node p = root;

            for (int i = 0; i < S.length(); ++i) {
                int x = S.charAt(i) - 'a';

                if (p.links[x] == null)
                    return i;

                p = p.links[x];
            }

            return S.length();
        }
    }
}