Pagini recente » Cod sursa (job #2502349) | Cod sursa (job #2648854) | Cod sursa (job #1346908) | Cod sursa (job #846289) | Cod sursa (job #2022715)
import java.io.*;
import java.util.Arrays;
import java.util.Objects;
class TrieNode {
private TrieNode[] next = new TrieNode[26];
private int count = 0;
boolean hasNext() {
return Arrays.stream(next).anyMatch(Objects::nonNull);
}
boolean isPrefix() {
return count > 0 || Arrays.stream(next).filter(Objects::nonNull).count() > 1;
}
TrieNode insert(char c, boolean isLastIndex) {
int index = c - 'a';
if(next[index] == null) {
TrieNode newNode = new TrieNode();
next[index] = newNode;
}
if(isLastIndex)
++next[index].count;
return next[index];
}
boolean delete(String word, int charIndex) {
int index = word.charAt(charIndex) - 'a';
if(next[index] == null)
return false;
if(charIndex == word.length() - 1) {
if(--next[index].count == 0) {
next[index] = null;
return true;
}
return false;
} else {
if(next[index].delete(word, charIndex + 1) && next[index].count == 0 && !next[index].hasNext()) {
next[index] = null;
return true;
}
return false;
}
}
int count(String word, int charIndex) {
int index = word.charAt(charIndex) - 'a';
if(next[index] == null)
return 0;
if(charIndex == word.length() - 1)
return next[index].count;
else
return next[index].count(word, charIndex + 1);
}
int prefix(String word, int charIndex) {
int index = word.charAt(charIndex) - 'a';
if(charIndex == word.length() - 1)
return next[index].hasNext() ? charIndex + 1 : 0;
else
return Math.max(
isPrefix() ? charIndex : 0,
next[index] == null ? (hasNext() ? charIndex : 0) : next[index].prefix(word, charIndex + 1));
}
void print(int level) {
for(int i = 0; i < 26; ++i) {
if(next[i] != null) {
System.out.printf("Level %d edge %s count %d\n", level, (char)('a' + i), next[i].count);
next[i].print(level + 1);
}
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("trie.in"));
BufferedWriter bw = new BufferedWriter(new FileWriter("trie.out"));
TrieNode trieRoot = new TrieNode();
String line;
while((line = br.readLine()) != null) {
String s = line.substring(2);
switch (line.charAt(0)) {
case '0':
insert(trieRoot, s, 0);
break;
case '1':
trieRoot.delete(s, 0);
break;
case '2':
bw.write(trieRoot.count(s, 0) + "\n");
break;
case '3':
bw.write(trieRoot.prefix(s, 0) + "\n");
break;
}
}
br.close();
bw.close();
}
private static void insert(TrieNode node, String word, int index) {
if(index < word.length())
insert(node.insert(word.charAt(index), index == word.length() - 1), word, index + 1);
}
}