fork(1) download
  1.  
  2. import java.io.*;
  3. import java.util.*;
  4.  
  5. /**
  6.  *
  7.  * @author Bassem Ehab
  8.  */
  9. public class Main {
  10.  
  11. public static void main(String[] args) throws IOException {
  12. int testcases = Integer.parseInt(input.readLine());
  13. HashMap<Integer, Boolean> visited = new HashMap<>();
  14. HashMap<Character, Integer> conv = new HashMap<>();
  15. ArrayList<LinkedList<Integer>> graph = new ArrayList<>();
  16. input.readLine();
  17. while (testcases-- > 0) {
  18. //StringTokenizer line = new StringTokenizer(input.readLine());
  19. String M = input.readLine();
  20. int count = 0;
  21. if (!conv.containsKey(M.charAt(0))) {
  22. conv.put(M.charAt(0), count++);
  23. graph.add(conv.get(M.charAt(0)), new LinkedList<Integer>());
  24. if (!visited.containsKey(conv.get(M.charAt(0)))) {
  25. visited.put(conv.get(M.charAt(0)), false);
  26. }
  27. }
  28. while (input.ready()) {
  29. M = input.readLine();
  30. if (M.isEmpty())break;
  31. if (!conv.containsKey(M.charAt(0))) {
  32. conv.put(M.charAt(0), count++);
  33. if (!visited.containsKey(conv.get(M.charAt(0)))) {
  34. visited.put(conv.get(M.charAt(0)), false);
  35. }
  36. }
  37. if (!conv.containsKey(M.charAt(1))) {
  38. conv.put(M.charAt(1), count++);
  39. if (!visited.containsKey(conv.get(M.charAt(1)))) {
  40. visited.put(conv.get(M.charAt(1)), false);
  41. }
  42. }
  43. if (graph.size() >= conv.get(M.charAt(0)) + 1) {
  44. graph.get(conv.get(M.charAt(0))).add(conv.get(M.charAt(1)));
  45. } else {
  46. graph.add(conv.get(M.charAt(0)), new LinkedList<Integer>());
  47. graph.get(conv.get(M.charAt(0))).add(conv.get(M.charAt(1)));
  48. }
  49. if (graph.size() >= conv.get(M.charAt(1)) + 1) {
  50. graph.get(conv.get(M.charAt(1))).add(conv.get(M.charAt(0)));
  51. } else {
  52. graph.add(conv.get(M.charAt(1)), new LinkedList<Integer>());
  53. graph.get(conv.get(M.charAt(1))).add(conv.get(M.charAt(0)));
  54. }
  55. }
  56. count = 0;
  57. for (int i = 0; i < visited.size(); ++i) {
  58. if (!visited.get(i)) {
  59. visited.put(i, true);
  60. Queue<Integer> temp = new LinkedList<>();
  61. temp.add(i);
  62. while (!temp.isEmpty()) {
  63. int x = temp.poll();
  64. visited.put(x, true);
  65. for (Integer get : graph.get(x)) {
  66. if (!visited.get(get)) {
  67. temp.add(get);
  68. }
  69. }
  70. }
  71. count++;
  72. }
  73. }
  74. System.out.println(count);
  75. if (testcases >= 1)System.out.println();
  76. conv.clear();
  77. visited.clear();
  78. graph.clear();
  79. }
  80. }
  81. }
  82.  
Success #stdin #stdout 0.06s 380160KB
stdin
1

E
AB
CE
DB
EC
stdout
2