fork(2) download
  1.  
  2.  
  3.  
  4.  
  5. import java.io.*;
  6. import java.util.*;
  7. class CSTREET
  8. {
  9. public static void main(String args[])
  10. throws IOException
  11. {
  12. int t=Integer.parseInt(br.readLine());
  13. while(t--!=0)
  14. {
  15. HashMap<Integer,ArrayList<String>> Map=new HashMap<Integer,ArrayList<String>>();
  16. ArrayList<Integer> V=new ArrayList<Integer>();
  17.  
  18.  
  19. int p=Integer.parseInt(br.readLine());
  20. int n=Integer.parseInt(br.readLine());
  21. int m=Integer.parseInt(br.readLine());
  22. for(int i=0;i<m;i++)
  23. {
  24. String in[]=br.readLine().split("\\s(?=\\S*$)");
  25. int cost=p*Integer.parseInt(in[1]);
  26. if(!Map.containsKey(cost))
  27. {
  28. ArrayList<String> al=new ArrayList<String>();
  29. al.add(in[0]);
  30. Map.put(cost, al);
  31. }
  32. else
  33. {
  34. ArrayList<String> get=Map.get(cost);
  35. get.add(in[0]);
  36. Map.put(cost,get);
  37. }
  38. }
  39. //iterate
  40. long sum=0;
  41.  
  42. Map<Integer,ArrayList<String>> map = new TreeMap<Integer,ArrayList<String>>(Map);//sorting by keys
  43.  
  44. Iterator it=map.entrySet().iterator();
  45. while(it.hasNext())
  46. {
  47. Map.Entry<Integer, ArrayList<String>> pairs=(Map.Entry<Integer, ArrayList<String>>)it.next() ;
  48. int cost=pairs.getKey();
  49. ArrayList<String> edges=pairs.getValue();// there can be multiple edges having single cost
  50.  
  51. Iterator<String> i=edges.iterator();
  52. while(i.hasNext())
  53. {
  54. String edge= i.next();
  55. String s[]=edge.split(" ");
  56. int u=Integer.parseInt(s[0]);
  57. int v=Integer.parseInt(s[1]);
  58.  
  59. if(V.contains(u) && V.contains(v))// neglect this edge if part of same set V
  60. {
  61. continue;
  62. }
  63. else if( V.contains(u) && !V.contains(v) )
  64. {
  65. V.add(v);
  66. sum+=cost;
  67. }
  68. else if( !V.contains(u) && V.contains(v) )
  69. {
  70. V.add(u);
  71. sum+=cost;
  72. }
  73. else if( !V.contains(u) && !V.contains(v) )
  74. {
  75. V.add(u);
  76. V.add(v);
  77. sum+=cost;
  78. }
  79.  
  80. }
  81.  
  82. }
  83.  
  84. System.out.println(sum);
  85.  
  86. }
  87. }
  88. }
Success #stdin #stdout 0.07s 380224KB
stdin
1
2
5
7
1 2 1
2 3 2
2 4 6
5 2 1
5 1 3
4 5 2
3 4 3
stdout
12