fork(1) download
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.StringTokenizer;
  10.  
  11.  
  12. public class Main
  13. {
  14.  
  15. public static class city
  16. {
  17. String c1;
  18. city next;
  19. int val;
  20.  
  21. public city(String a,int v)
  22. {
  23. c1 = a;
  24. val = v;
  25. next = null;
  26. }
  27. }
  28.  
  29. static int T,tot,x,cost,ans;
  30. static StringTokenizer t;
  31. static String city1,city2;
  32. static HashMap<String,city> map = new HashMap<String,city>();
  33. static HashMap<String,Integer> head = new HashMap<String,Integer>();
  34. static List<String> sol = new ArrayList<String>();
  35.  
  36. public static void main(String[] args) throws NumberFormatException, IOException
  37. {
  38. T = Integer.parseInt(br.readLine());
  39.  
  40. while(T-- >0)
  41. {
  42. tot = Integer.parseInt(br.readLine());
  43. tot--;
  44.  
  45. cost = ans = 0;
  46.  
  47. if(tot==0) System.out.println("0$");
  48. else
  49. {
  50. for(x=0;x<tot;x++)
  51. {
  52. t = new StringTokenizer(br.readLine());
  53.  
  54. city1 = t.nextToken();
  55. city2 = t.nextToken();
  56. cost = Integer.parseInt(new StringTokenizer(t.nextToken(),"$").nextToken());
  57. ans += cost;
  58.  
  59.  
  60. map.put(city1, new city(city1,-1));
  61.  
  62. if(map.containsKey(city2)) map.get(city2).val = cost;
  63. else map.put(city2, new city(city2,cost));
  64.  
  65. map.get(city1).next = map.get(city2);
  66.  
  67. if(!head.containsKey(city1)) head.put(city1, 1);
  68. head.put(city2, 2);
  69.  
  70.  
  71. }
  72.  
  73. String start = null;
  74. Iterator it = head.entrySet().iterator();
  75. while (it.hasNext())
  76. {
  77. Map.Entry pairs = (Map.Entry)it.next();
  78.  
  79. if((Integer)pairs.getValue()==1)
  80. {
  81. start = (String) (pairs.getKey());
  82. break;
  83. }
  84. }
  85.  
  86. for(x=0;x<tot;x++)
  87. {
  88. if(map.get(start).next!=null)
  89. {
  90. sol.add(start+" "+map.get(start).next.c1+" "+map.get(start).next.val+"$");
  91. start = map.get(start).next.c1;
  92. }
  93. }
  94. sol.add(ans+"$");
  95. }
  96. for(x=0;x<sol.size();x++) System.out.println(sol.get(x));
  97. }
  98. }}
Runtime error #stdin #stdout 0.03s 245632KB
stdin
2
2
A B 100
2
B A 100
stdout
A B 100$
100$