Collision
Time Limit: 15000/15000 MS (Java/Others) Memory Limit: 512000/512000 K (Java/Others)
Total Submission(s): 864 Accepted Submission(s): 206
Problem Description Matt is playing a naive computer game with his deeply loved pure girl.
The playground is a rectangle with walls around. Two balls are put in different positions inside the rectangle. The balls are so tiny that their volume can be ignored. Initially, two balls will move with velocity (1, 1). When a ball collides with any side of the rectangle, it will rebound without loss of energy. The rebound follows the law of refiection (i.e. the angle at which the ball is incident on the wall equals the angle at which it is reflected).
After they choose the initial position, Matt wants you to tell him where will the two balls collide for the first time.
Input The first line contains only one integer T which indicates the number of test cases.
For each test case, the first line contains two integers x and y. The four vertices of the rectangle are (0, 0), (x, 0), (0, y) and (x, y). (1 ≤ x, y ≤ 105)
�The next line contains four integers x1, y1, x2, y2. The initial position of the two balls is (x1, y1) and (x2, y2). (0 ≤ x1, x2 ≤ x; 0 ≤ y1, y2 ≤ y)
Output For each test case, output “Case #x:” in the first line, where x is the case number (starting from 1).
In the second line, output “Collision will not happen.” (without quotes) if the collision will never happen. Otherwise, output two real numbers xc and yc, rounded to one decimal place, which indicate the position where the two balls will first collide.
Sample Input
3
10 10
1 1 9 9
10 10
0 5 5 10
10 10
1 0 1 10
Sample Output
Case #1:
6.0 6.0
Case #2:
Collision will not happen.
Case #3:
6.0 5.0
Hint
In first example, two balls move from (1, 1) and (9, 9) both with velocity (1, 1), the ball starts from (9, 9) will rebound at point (10, 10) then move with velocity (−1, −1). The two balls will meet each other at (6, 6).
Source 2014ACM/ICPC亚洲区北京站-重现赛(感谢北师和上交)
解析:扩展欧几里得。参考[http://www.cnblogs.com/TenderRun/p/5943453.html](http://www.cnblogs.com/TenderRun/p/5943453.html)。
``` #include
ll ta,tb,x,y, time;
int T,n,m,x1,y1,x2,y2;
ll extgcd(ll a, ll b, ll &x, ll &y)
{
if(b == 0){
x = 1;
y = 0;
return a;
}
ll q = extgcd(b, a%b, y, x);
y -= a/b*x;
return q;
}
int main()
{
int cn = 0;
scanf("%d",&T);
while(T--){
scanf("%d%d%d%d%d%d", &n, &m, &x1, &y1, &x2, &y2);
n = 2 ;m = 2; x1 = 2; y1 = 2; x2 = 2; y2 = 2;
ta = n-(x1+x2)/2; tb = m-(y1+y2)/2;
printf("Case #%d:
",++cn);
time = -1;
if(x1 == x2 && y1 == y2) time = 0;
else if(y1y2) time = ta;
else if(x1x2) time = tb;
else{
ll d = extgcd(n,m,x,y);
if((tb-ta)%d==0){
x = (tb-ta)/dx;
x = (x%(m/d)+m/d)%(m/d);
time = ta+nx;
}
}
if(time == -1)
puts("Collision will not happen.");
else{
x1 = (x1+time)%(2n); y1 = (y1+ time)%(2m);
if(x1>n) x1 = 2n-x1;
if(y1>m) y1 = 2m-y1;
printf("%.1f %.1f
", x1/2.0, y1/2.0);
}
}
return 0;
}