fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. static class TrieNode {
  11. boolean isEow;
  12. TrieNode children[];
  13. TrieNode() {
  14. children=new TrieNode[26];
  15. }
  16. }
  17. static class TrieFunctions {
  18. private TrieNode insert(TrieNode r,int idx,char w[]) {
  19. if(r==null) {
  20. r=new TrieNode();
  21. }
  22. if (idx == w.length) {
  23. r.isEow = true;
  24. return r;
  25. }
  26. char ch=w[idx];
  27. r.children[ch-'a']=insert(r.children[ch-'a'],idx+1,w);
  28. return r;
  29. }
  30. void insert(TrieNode r,char w[]) {
  31. r=insert(r,0,w);
  32. }
  33. private void print(TrieNode r, String word) {
  34. if (r.isEow)
  35. System.out.println(word);
  36.  
  37. for (int i = 0; i < 26; i++) {
  38. if (r.children[i] != null) {
  39. print(r.children[i], word + (char) (i + 'a'));
  40. }
  41. }
  42. }
  43.  
  44. void printAllWords(TrieNode r) {
  45. print(r, "");
  46. }
  47. }
  48. public static void main (String[] args) throws java.lang.Exception
  49. {
  50. // your code goes here
  51. Scanner sc = new Scanner(System.in);
  52. int t = sc.nextInt();
  53. while(t-- != 0){
  54. TrieNode r = new TrieNode();
  55. TrieFunctions tf = new TrieFunctions();
  56. int n = sc.nextInt();
  57. while(n-- != 0){
  58. String s = sc.next();
  59. tf.insert(r, s.toCharArray());
  60. }
  61. tf.printAllWords(r);
  62. }
  63. }
  64. }
Success #stdin #stdout 0.15s 60784KB
stdin
2
10
app
dog
fllev
dxo
dxo
dxo
lri
lri
lri
dxo
4
gkui
nyf
opyuy
tady
stdout
app
dog
dxo
fllev
lri
gkui
nyf
opyuy
tady