fork(9) download
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.HashMap;
  4. import java.util.HashSet;
  5. import java.util.Map;
  6. import java.util.Set;
  7.  
  8. class Traveling {
  9.  
  10. private static final int INPUT_LEN = 2 + 2 + 10 * (4 + 2 + 5000 * (50 + 1 + 50 + 1 + 5 + 2));
  11.  
  12. public static void main(String[] args) throws Exception {
  13. BufferedReader br = new BufferedReader(new InputStreamReader(System.in), INPUT_LEN);
  14. int T = Integer.parseInt(br.readLine());
  15. Map<String, String> fromMap = new HashMap<String, String>();
  16. Map<String, String> fromPriceMap = new HashMap<String, String>();
  17. Set<String> toMap = new HashSet<String>();
  18. StringBuilder buff = new StringBuilder();
  19. while (T-- > 0) {
  20. int N = Integer.parseInt(br.readLine());
  21. long sum = 0;
  22. { // solve test case
  23. fromMap.clear();
  24. toMap.clear();
  25. while (--N > 0) {
  26. String[] parts = br.readLine().split(" ");
  27. fromMap.put(parts[0], parts[1]);
  28. fromPriceMap.put(parts[0], parts[2]);
  29. toMap.add(parts[1]);
  30. sum += parse(parts[2]);
  31. }
  32. // get first
  33. Set<String> firstSet = new HashSet<String>(fromMap.keySet());
  34. firstSet.removeAll(toMap);
  35. String from = firstSet.iterator().next();
  36. // iterate and print
  37. buff.setLength(0);
  38. String next = fromMap.get(from);
  39. while (next != null) {
  40. buff.append(from).append(' ').append(next).append(' ').append(fromPriceMap.get(from)).append('\n');
  41. from = next;
  42. next = fromMap.get(from);
  43. }
  44. buff.append(sum).append("$\n");
  45. System.out.println(buff.toString());
  46. }
  47. }
  48. }
  49.  
  50. private static long parse(String price) {
  51. return Integer.parseInt(price.substring(0, price.length() - 1));
  52. }
  53. }
Success #stdin #stdout 0.04s 245632KB
stdin
2
2
A B 100$
2
B A 100$
stdout
A B 100$
100$

B A 100$
100$