fork download
  1. import java.util.*;
  2.  
  3. class ComponentConverter {
  4.  
  5. static class ComponentRatio {
  6. String name;
  7. double ratio;
  8.  
  9. ComponentRatio(String name, double ratio) {
  10. this.name = name;
  11. this.ratio = ratio;
  12. }
  13. }
  14.  
  15. public static void main(String[] args) {
  16. Scanner sc = new Scanner(System.in);
  17.  
  18.  
  19. String[] comps = sc.nextLine().split(",");
  20. int n = comps.length;
  21. List<String> components = new ArrayList<>();
  22. for (String comp : comps)
  23. components.add(comp.trim());
  24.  
  25.  
  26. Double[][] matrix = new Double[n][n];
  27. for (int i = 0; i < n; i++) matrix[i][i] = 1.0;
  28.  
  29.  
  30. while (sc.hasNextLine()) {
  31. String line = sc.nextLine().trim();
  32. if (line.isEmpty()) break;
  33.  
  34. String[] parts = line.split(" is ");
  35. String from = parts[0].trim();
  36. String toPart = parts[1].trim();
  37.  
  38. int qty = Integer.parseInt(toPart.replaceAll("[^0-9]", ""));
  39. String to = toPart.replaceAll("[0-9]", "").trim();
  40.  
  41. int i = components.indexOf(from);
  42. int j = components.indexOf(to);
  43.  
  44. matrix[i][j] = (double) qty;
  45. matrix[j][i] = 1.0 / qty;
  46. }
  47.  
  48.  
  49. for (int k = 0; k < n; k++) {
  50. for (int i = 0; i < n; i++) {
  51. for (int j = 0; j < n; j++) {
  52. if (matrix[i][k] != null && matrix[k][j] != null && matrix[i][j] == null) {
  53. matrix[i][j] = matrix[i][k] * matrix[k][j];
  54. }
  55. }
  56. }
  57. }
  58.  
  59.  
  60. int rootIndex = -1;
  61. for (int i = 0; i < n; i++) {
  62. boolean isRoot = true;
  63. for (int j = 0; j < n; j++) {
  64. if (matrix[i][j] == null || matrix[i][j] < 1.0) {
  65. isRoot = false;
  66. break;
  67. }
  68. }
  69. if (isRoot) {
  70. rootIndex = i;
  71. break;
  72. }
  73. }
  74.  
  75. if (rootIndex == -1) {
  76. System.out.println("No root component found.");
  77. return;
  78. }
  79.  
  80.  
  81. List<ComponentRatio> ratios = new ArrayList<>();
  82. for (int i = 0; i < n; i++) {
  83. ratios.add(new ComponentRatio(components.get(i), matrix[rootIndex][i]));
  84. }
  85.  
  86.  
  87. ratios.sort(Comparator.comparingDouble(r -> r.ratio));
  88.  
  89. StringBuilder sb = new StringBuilder();
  90. for (ComponentRatio r : ratios) {
  91. if (sb.length() > 0) sb.append(" equals ");
  92. sb.append((int)Math.round(r.ratio)).append(r.name);
  93. }
  94.  
  95. System.out.println(sb.toString());
  96. }
  97. }
  98.  
Success #stdin #stdout 0.18s 56720KB
stdin
Shelve,Draw,Rack,Wardrobe
Shelve is 2 Draw
Rack is 3 Shelve
Wardrobe is 36 Draw
stdout
1Wardrobe equals 6Rack equals 18Shelve equals 36Draw