字典树

前段时间,在计蒜客学了字典树,做了道题目,挺有趣的。

题目:原题地址

蒜头君作为蒜厂的工程师,在开发网站时不小心写出了一个 Bug:当用户输入密码时,如果既和自己的密码一致,也同时是另一个用户密码的 前缀 时,用户会跳转到 404 页。

然而蒜头君坚称:我们的用户那么少,怎么可能触发这个 Bug……

机智的你,能不能帮蒜头君确认一下这个 Bug 到底会不会触发呢?

样例输入

第一行输入一个整数 n(1 \leq n \leq 233333)n(1n233333),表示蒜厂网站的用户数。接下来一共 nn 行,每行一个由小写字母a-z组成的字符串,长度不超过 1010,表示每个用户的密码。蒜厂的数据库容量太小,所有密码长度加起来小于 466666466666。

样例输出

如果触发了 Bug 则输出一行Bug!,否则输出一行Good Luck!

样例输入1

3
abc
abcdef
cdef

样例输出1

Bug!

样例输入2

3
abc
bcd
cde

样例输出2

Good Luck!


关于字典树的学习,我想计蒜客上的讲解比我说的要详细,有想要学习可以去那看看😊

这里我就直接贴代码了:
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static int MAX_N = 1000000;
    static int MAX_C = 26;
    static int tot = 0;
    static int[] ch;
    static int[][] cnt;

    public static void init() {
        cnt = new int[MAX_N][];
        ch = new int[MAX_N];

        Arrays.fill(ch, 0);
        Arrays.fill(cnt, null);
    }

    public static void insert(String str) {
        int p = 0;
        for (int i = 0; i < str.length(); i++) {
            if (cnt[p] == null) {
                cnt[p] = new int[MAX_C];
                Arrays.fill(cnt[p], -1);
            }
            if (cnt[p][str.charAt(i) - 'a'] == -1) {
                cnt[p][str.charAt(i) - 'a'] = ++tot;
                ch[p]++;
            }
            p = cnt[p][str.charAt(i) - 'a'];
        }
        ch[p]++;
    }

    public static int find(String str) {
        int p = 0;
        for (int i = 0; i < str.length(); i++) {
            if (cnt[p] == null) {
                return 0;
            }
            if ((p = cnt[p][str.charAt(i) - 'a']) == -1) {
                return 0;
            }
        }
        return ch[p];
    }

    public static void main(String[] args) {
        init();
        Scanner scn = new Scanner(System.in);
        int n = scn.nextInt();
        scn.nextLine();
        String[] strs = new String[n];
        for (int i = 0; i < n; i++) {
            strs[i] = scn.nextLine();
            insert(strs[i]);
        }

        for (int i = 0; i < n; i++) {
            if (find(strs[i]) > 1) {
                System.out.println("Bug!");
                return;
            }
        }
        System.out.println("Good Luck!");
    }
}

 

posted @ 2017-08-21 17:39  夏天的冬天  阅读(192)  评论(0编辑  收藏  举报