http://hihocoder.com/problemset/problem/1014
构建一棵字典树,然后进行字符串匹配就可以了
这个题我本来是想用java做,但是做了后才发现有那么多的错误,java还是有待加强啊
两份代码都基本是一样的,只不过语法规则的区别
1014 | Trie树 | AC | G++ | 1788ms | 114MB |
1014 | Trie树 | AC | Java | 9548ms | 102MB |
1 import java.util.Scanner; 2 3 class Node { 4 int[] next = new int[26];; 5 int cnt = 0;; 6 void inti() { 7 for (int i = 0; i < 26; i++) 8 next[i] = -1; 9 } 10 } 11 12 public class Main { 13 14 private static Node[] node = new Node[1000005]; 15 static int cnt; 16 public static void main(String[] args) { 17 int a, b; 18 Scanner cin = new Scanner(System.in); 19 while (cin.hasNext()) { 20 cnt = 1; 21 a = cin.nextInt(); 22 String str; 23 node[0] = new Node(); 24 node[0].inti(); 25 for (int i = 0; i < a; i++) { 26 str = cin.next(); 27 insert(str); 28 } 29 b = cin.nextInt(); 30 for (int i = 0; i < b; i++) { 31 str = cin.next(); 32 Find(str); 33 } 34 } 35 } 36 37 static void insert(String s) { 38 int p = 0; 39 for (int i = 0; i < s.length(); i++) { 40 int tmp = s.charAt(i) - 'a'; 41 if (node[p].next[tmp] == -1) { 42 if(node[cnt]==null){ 43 node[cnt] = new Node(); 44 node[cnt].inti(); 45 } 46 node[p].next[tmp] = cnt++; 47 } 48 p = node[p].next[tmp]; 49 if(node[p]==null){ 50 node[p] = new Node(); 51 node[p].inti(); 52 } 53 node[p].cnt++; 54 } 55 } 56 57 static void Find(String s) { 58 int p = 0; 59 for (int i = 0; i < s.length(); i++) { 60 int tmp = s.charAt(i) - 'a'; 61 if (node[p].next[tmp] == -1) { 62 System.out.println("0"); 63 return; 64 } 65 p = node[p].next[tmp]; 66 } 67 System.out.println(node[p].cnt); 68 } 69 }
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 6 class Node { 7 public : 8 int next[26]; 9 int cnt = 0; 10 void inti() { 11 for (int i = 0; i < 26; i++) 12 next[i] = -1; 13 } 14 }; 15 Node node[1000005]; 16 int cnt; 17 void insert(string s) { 18 int p = 0; 19 for (int i = 0; i < s.length(); i++) { 20 int tmp = s[i] - 'a'; 21 if (node[p].next[tmp] == -1) { 22 node[cnt].inti(); 23 node[p].next[tmp] = cnt++; 24 } 25 p = node[p].next[tmp]; 26 node[p].cnt++; 27 } 28 } 29 30 void Find(string s) { 31 int p = 0; 32 for (int i = 0; i < s.length(); i++) { 33 int tmp = s[i] - 'a'; 34 if (node[p].next[tmp] == -1) { 35 cout << "0" << endl; 36 return; 37 } 38 p = node[p].next[tmp]; 39 } 40 cout << node[p].cnt << endl; 41 } 42 int main() { 43 int a, b; 44 cnt = 1; 45 cin >> a; 46 string str; 47 node[0].inti(); 48 for (int i = 0; i < a; i++) { 49 cin >> str; 50 insert(str); 51 } 52 cin >> b; 53 for (int i = 0; i < b; i++) { 54 cin >> str; 55 Find(str); 56 } 57 }