洛谷 P2580 于是他错误的点名开始了 Java

import java.util.*;
import java.io.*;

public class Main{

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));


    public static void main(String[] args) throws IOException {
        int n,m;
        n = Integer.parseInt(br.readLine());
        Operation o = new Operation();
        HashSet hash = new HashSet<>();
        for(int i = 0 ; i < n ; i++) {
            String str = br.readLine();
            o.Insert(str);
        }
        m = Integer.parseInt(br.readLine());
        for(int i = 0 ; i < m ; i++) {
            String str = br.readLine();
            if(hash.contains(str)) {
                out.write("REPEAT\n");
                continue;
            }
            hash.add(str);
            if(o.Search(str)) {
                out.write("OK\n");
            }
            else {
                out.write("WRONG\n");
            }
        }
        out.flush();
        out.close();
        br.close();
    }
}

class Operation{

    static Tire root = new Tire();

    public void Insert(String str) {
        Tire node = root;
        for(int i = 0 ; i < str.length() ; i++) {
            int index = str.charAt(i) - 'a';
            if(node.tire[index] == null) {
                node.tire[index] = new Tire();
            }
            node = node.tire[index];
        }
        node.cnt++;
    }

    public boolean Search(String str) {
        Tire node = root;
        for(int i = 0 ; i < str.length() ; i++) {
            int index = str.charAt(i) - 'a';
            if(node.tire[index] == null) {
                return false;
            }
            node = node.tire[index];
        }
        return node.cnt > 0;
    }
}

class Tire{
    int cnt;
    Tire[] tire = new Tire[26];
}

一道简单的Tire树

你可能感兴趣的:(洛谷刷题之旅,java,算法)