Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/rhino
- importPackage(java.util);
- importPackage(java.lang);
- function accumulate(f,list,init){
- // refactored into iterative code - stack overflow with recursion :-S
- var ret=init;
- for(i=0;i<list.length;i++)
- ret=f(ret,list[i]);
- return ret;
- }
- function sum(list){
- // accumulate with addition to get the sum
- return accumulate((function(x,y){return x+y;}),list,0);
- }
- function solve(sizes,rides, k){
- r=rides
- money=[]
- seen={}
- cur=0
- step=0
- // simulate until a cycle is found
- while (!(cur in seen) && r>0){
- left=k
- seen[cur]=step
- step+=1
- r-=1
- old_cur=cur
- mon=0
- groups_left=sizes.length
- while (left>=sizes[cur] && groups_left>0){
- mon+=sizes[cur]
- left-=sizes[cur]
- cur=(cur+1)%sizes.length
- groups_left-=1
- }
- money.push(mon)
- }
- total_money=sum(money)
- if (r==0){
- // all rides taken up => no cycles yet => just return whatever money we got
- return total_money
- }
- cycle_start=seen[cur]
- cycle_money=sum(money.slice(cycle_start))
- startup=total_money-cycle_money
- cycle_len=money.slice(cycle_start).length
- // first few may not be part of the cycle
- rides-=cycle_start
- cycles=Math.floor(rides/cycle_len)
- extras=rides%cycle_len
- // money from rides not part of the cycle
- // + money per cycle * number of cycles
- // + money from the last few rides that don't form a complete sysle
- return startup+cycle_money*cycles+sum(money.slice(cycle_start,cycle_start+extras))
- }
- function main(){
- cin=Scanner(System['in']);
- cases=cin.nextInt();
- for (cas=1;cas<=cases;cas++){
- R=cin.nextInt();
- k=cin.nextInt();
- N=cin.nextInt();
- group_sizes=[];
- for(i=0;i<N;i++) group_sizes.push(cin.nextInt());
- print("Case #"+cas+": "+solve(group_sizes,R,k));
- }
- }
- main();
Add Comment
Please, Sign In to add comment