Velocities of balls

2.4

20 votes
, Algorithms, Linear Search, Simulation
Problem

There are n balls along a number line, each ball is represented by a point on the line. Ball i moves at velocity vi (vi0) along this number line and is initially at point xi.

When two balls collide (occupy the same point along the number line), their velocities switch. For example, if ball i with velocity 2 collides with ball j with velocity 3, ball i will have velocity 3 and ball j will have velocity 2 after the collision.

Given each ball's initial distinct position and velocity, find for each ball i the sum of the floor of the times that ball i collides with another ball. Formally, ball i collides with another ball k times in total at times t1,t2,tk. Print, ki=1ti for each ball.

It is guaranteed that whenever two balls i,j collide, the signs of their velocities will be different (vivj<0).

Input format

  • The first line of the input contains a single integer t denoting the number of test cases.
  • The first line of each test case contains a single integer n denoting the number of balls.
  • The second line of each test case contains n integers xi denoting the initial position of ball i.
  • The third line of each test case contains n integers vi denoting the velocity of ball i.

Output format

Print n integers denoting the ith being the sum of the floors of each time ball i collides with another ball.

Constraints

1t100

1n2000

|xi|2000

0<|vi|2000

  • It is guaranteed that, in the given input, whenever two balls collide the signs of their velocities will be different.

  • It is guaranteed that the sum of n over all test cases is less than or equal to 2000.

  • No two pairs of balls collide at the same place at the same time.

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

In the first test case, the balls never collide so the total sum of times will be 0.

In the second test case, the ball collides exactly ones at t=1, so the sum of the floor of times for each ball will be 1.

In the third test case, the first collision happens between the 2nd and 3rd balls at time 43. When they collide, the second ball and third ball switch velocities so the second ball is now traveling at velocity 2 and the third ball is now traveling at velocity 1. The third ball never hits anything else so it's final value is 43=1. The second ball then hits the first ball at t=103 and then no balls ever collide again. Thus, the answer for the second ball is 43+103=4 and the answer for the second ball is simply 103=3.

Editor Image

?