Codeforces 724C Ray Tracing 扩展欧几里得

标签: 解题报告 数学


原题见CF 724C

n*m的矩形内有k个点,四周有围墙围起来。从(0,0)45度发射小球,速度为 2 每次遇到墙都正常反弹,直到射到顶点被吸收。问每个点第一次被经过的时刻。


分析

把矩形对称展开,最后小球在横纵坐标均为 maxx=mn/gcd(m,n) 处被吸收。
原坐标为 (x,y) 的小球经过轴对称展开,其坐标为 (2kn±x,2sm±y),k,s .要使得在吸收前经过点,则坐标必须在线段(0, 0)到(maxx, mxx)之间。
即要解方程 2kn±x=2sm±y ,求为正最小的 2kn±x 。利用扩展欧几里得解方程。

求ax+by=c最小正整数解,坑点:ran<0时不搞成正数会出错!

LL equation(LL a, LL b, LL c, LL &x, LL &y)
{
    LL g = extend_Euclid(a, b, x, y);
    if(c % g) return -1;
    LL ran = b / g;
    x *= c/g;
    if(ran < 0) ran = -ran; //wa point
    x = (x%ran + ran) % ran;
    return 0;
}

代码

/*--------------------------------------------
 * File Name: CF 724C
 * Author: Danliwoo
 * Mail: [email protected]
 * Created Time: 2016-10-08 23:37:05
--------------------------------------------*/

#include 
using namespace std;
#define LL long long
LL n, m;
LL extend_Euclid(LL a, LL b, LL &x, LL &y){
    if(b==0){
        x = 1; y = 0;
        return a;
    }
    LL r = extend_Euclid(b, a%b, y, x);
    y -= a/b*x;
    return r;
}
LL equation(LL a, LL b, LL c, LL &x, LL &y)
{
    LL g = extend_Euclid(a, b, x, y);
    if(c % g) return -1;
    LL ran = b / g;
    x *= c/g;
    if(ran < 0) ran = -ran;
    x = (x%ran + ran) % ran;
    return 0;
}
LL gao(LL dx, LL dy, LL M) {
    LL k, s;
    if(equation(2*n, -2*m, -dx+dy, k, s) == -1)
        return M + 1;
    LL tx = 2 * k * n + dx;
    if(tx < 0 || tx > M) return M + 1;
    return tx;
}
LL minL(LL a, LL b) {
    return a < b ? a : b;
}
LL solve(LL x, LL y) {
    LL g = __gcd(n, m);
    LL maxx = 1LL * m / g * n;
    LL ans = maxx + 1;
    ans = minL(ans, gao(-x, -y, maxx));
    ans = minL(ans, gao(-x, y, maxx));
    ans = minL(ans, gao(x, -y, maxx));
    ans = minL(ans, gao(x, y, maxx));
    if(ans == maxx + 1) return -1;
    return ans;
}
int main() {
    int k;
    while(~scanf("%I64d%I64d%d", &n, &m, &k)) {
        for(int i = 0;i < k;i++) {
            LL x, y;
            scanf("%I64d%I64d", &x, &y);
            printf("%I64d\n", solve(x, y));
        }
    }
    return 0;
}

你可能感兴趣的:(ACM-解题报告,--数学)