Guest User

Untitled

a guest
May 25th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. #! /usr/bin/rhino
  2.  
  3. importPackage(java.util);
  4. importPackage(java.lang);
  5.  
  6. function accumulate(f,list,init){
  7. // refactored into iterative code - stack overflow with recursion :-S
  8. var ret=init;
  9. for(i=0;i<list.length;i++)
  10. ret=f(ret,list[i]);
  11. return ret;
  12. }
  13.  
  14. function sum(list){
  15. // accumulate with addition to get the sum
  16. return accumulate((function(x,y){return x+y;}),list,0);
  17. }
  18.  
  19. function solve(sizes,rides, k){
  20. r=rides
  21. money=[]
  22. seen={}
  23. cur=0
  24. step=0
  25.  
  26. // simulate until a cycle is found
  27. while (!(cur in seen) && r>0){
  28. left=k
  29. seen[cur]=step
  30. step+=1
  31. r-=1
  32. old_cur=cur
  33. mon=0
  34. groups_left=sizes.length
  35. while (left>=sizes[cur] && groups_left>0){
  36. mon+=sizes[cur]
  37. left-=sizes[cur]
  38. cur=(cur+1)%sizes.length
  39. groups_left-=1
  40. }
  41. money.push(mon)
  42. }
  43.  
  44. total_money=sum(money)
  45.  
  46. if (r==0){
  47. // all rides taken up => no cycles yet => just return whatever money we got
  48. return total_money
  49. }
  50.  
  51. cycle_start=seen[cur]
  52. cycle_money=sum(money.slice(cycle_start))
  53.  
  54. startup=total_money-cycle_money
  55. cycle_len=money.slice(cycle_start).length
  56.  
  57. // first few may not be part of the cycle
  58. rides-=cycle_start
  59.  
  60. cycles=Math.floor(rides/cycle_len)
  61. extras=rides%cycle_len
  62.  
  63. // money from rides not part of the cycle
  64. // + money per cycle * number of cycles
  65. // + money from the last few rides that don't form a complete sysle
  66. return startup+cycle_money*cycles+sum(money.slice(cycle_start,cycle_start+extras))
  67. }
  68.  
  69. function main(){
  70. cin=Scanner(System['in']);
  71.  
  72. cases=cin.nextInt();
  73. for (cas=1;cas<=cases;cas++){
  74. R=cin.nextInt();
  75. k=cin.nextInt();
  76. N=cin.nextInt();
  77.  
  78. group_sizes=[];
  79. for(i=0;i<N;i++) group_sizes.push(cin.nextInt());
  80.  
  81. print("Case #"+cas+": "+solve(group_sizes,R,k));
  82. }
  83. }
  84.  
  85. main();
Add Comment
Please, Sign In to add comment