fork(1) download
  1. #会津大学オンラインジャッジ問1196 Bridge Removalに合格したコード一番速度の遅い部類
  2. #堀江伸一
  3. def commitCost(old1,now1)
  4. d=$cons[old1][now1]
  5. if 1<$cons[old1].size && 1<$cons[now1].size then
  6. d*=3
  7. end
  8. $cost[old1][now1]=d
  9. $cost[now1][old1]=d
  10. $cons[now1].each{|next1,d|
  11. next if next1==old1
  12. commitCost(now1,next1)
  13. }
  14. end
  15.  
  16. def calcAns(old1,now1,cost1)
  17. res=cost1
  18. $cost[now1].each{|next1,cost2|
  19. next if old1==next1
  20. if now1==next1 then
  21. res=[res,cost1].min
  22. else
  23. cost3=$cons[now1][next1]*2
  24. cost4=cost1-cost2+cost3
  25. res=[res,cost4].min
  26. t=calcAns(now1,next1,cost4)
  27. res=[res,t].min
  28. end
  29. }
  30. return res
  31. end
  32.  
  33. def f(n)
  34. $cons={}
  35. $root={}
  36. $cost={}
  37. xs=gets.split(" ").map{|e| e.to_i}
  38. ys=gets.split(" ").map{|e| e.to_i}
  39. 1.upto(n){|i|
  40. $cons[i]={}
  41. $cost[i]={}
  42. }
  43. from=2
  44. xs.zip(ys).each{|to,d|
  45. $cons[from][to]=d
  46. $cons[to][from]=d
  47. $cost[from][to]=0
  48. $cost[to][from]=0
  49. from+=1
  50. }
  51. $cons[1].each{|k,v|
  52. commitCost(1,k)
  53. }
  54.  
  55.  
  56. $allCost=0
  57. $cost.each{|k1,ks|
  58. $allCost+=ks.values.sum
  59. }
  60. 1.upto(n){|i|
  61. $cons[i][i]=0
  62. $cost[i][i]=0
  63. }
  64.  
  65. $allCost/=2
  66. ans=10**24
  67. all=[]
  68. 1.upto(n){|i|
  69. cost1=$allCost
  70. t=calcAns(i,i,cost1)
  71. ans=[t,ans].min
  72. }
  73. puts ans
  74. end
  75.  
  76. $cons={}
  77. $root={}
  78. $cost={}
  79. $allCost=0
  80. while true
  81. n=gets.to_i
  82. break if n==0
  83. f(n)
  84. end
Success #stdin #stdout 0.01s 8036KB
stdin
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
stdout
80
136
2