Codeforces 982E Billiard exgcd

时间:2022-09-09 05:05:33

Billiard

枚举终点, 对于每一个终点一共有四种周期的相遇方式, 枚举一下取最小的时间。

#include<bits/stdc++.h>
#define LL long long
#define LD long double
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ull unsigned long long using namespace std; const int N = 1e5 + ;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + ;
const double eps = 1e-;
const double PI = acos(-); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;}
template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < ) a += mod;}
template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;}
template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} LL x, y;
LL exgcd(LL a, LL b, LL &x, LL &y) {
if(!b) {
x = ; y = ;
return a;
} else {
LL gcd, t; gcd = exgcd(b, a % b, x, y);
t = x; x = y; y = t - (a / b) * y;
return gcd;
}
} LL n, m, sx, sy, vx, vy; LL gao(LL a, LL b, LL t1, LL t2) {
LL c = t2 - t1;
LL gcd = exgcd(a, b, x, y);
if(c % gcd) return INF;
x *= c / gcd; y *= c / gcd;
LL mo = abs(b / gcd);
x = (x % mo + mo) % mo;
return * n * x + t1;
} LL calc(LL sx, LL sy, LL vx, LL vy, LL tx, LL ty) {
LL t11 = , t12 = ;
LL t21 = , t22 = ;
if(vx > ) {
if(tx >= sx) t11 = tx - sx, t12 = t11 + * (n - tx);
else t11 = sx - tx + * (n - sx), t12 = t11 + * tx;
} else {
if(tx <= sx) t11 = sx - tx, t12 = t11 + * tx;
else t11 = tx - sx + * sx, t12 = t11 + * (n - tx);
}
if(vy > ) {
if(ty >= sy) t21 = ty - sy, t22 = t21 + * (m - ty);
else t21 = sy - ty + * (m - sy), t22 = t21 + * ty;
} else {
if(ty <= sy) t21 = sy - ty, t22 = t21 + * ty;
else t21 = ty - sy + * sy, t22 = t21 + * (m - ty);
}
LL tim = INF;
chkmin(tim, gao( * n, - * m, t11, t21));
chkmin(tim, gao( * n, - * m, t11, t22));
chkmin(tim, gao( * n, - * m, t12, t21));
chkmin(tim, gao( * n, - * m, t12, t22));
return tim;
} void print(int who) {
if(who == ) cout << "0 0" << "\n";
else if(who == ) cout << n << " " << "0\n";
else if(who == ) cout << "0 " << m << "\n";
else if(who == ) cout << n << " " << m << "\n";
else cout << "-1" << "\n";
exit();
} int main() {
cin >> n >> m >> sx >> sy >> vx >> vy;
if(!vx) {
if(sx == && vy == ) print();
else if(sx == && vy == -) print();
else if(sx == n && vy == ) print();
else if(sx == n && vy == -) print();
else print(-);
} else if(!vy) {
if(sy == && vx == ) print();
else if(sy == && vx == -) print();
else if(sy == m && vx == ) print();
else if(sy == m && vx == -) print();
else print(-);
} else {
LL tim = INF, who = -;
if(chkmin(tim, calc(sx, sy, vx, vy, , ))) who = ;
if(chkmin(tim, calc(sx, sy, vx, vy, n, ))) who = ;
if(chkmin(tim, calc(sx, sy, vx, vy, , m))) who = ;
if(chkmin(tim, calc(sx, sy, vx, vy, n, m))) who = ;
print(who);
}
return ;
} /*
*/