题解 P8854 【[POI2002] 超级马】

· · 题解

显然,只要我们通过这些向量拼出 (0, \pm 1) 和 (\pm 1, 0),就可以达成题目目标。

上述两类向量本质相同,现在考虑拼出 (0, \pm 1) 的情况。

但是直接考虑一堆向量拼起来又太麻烦,因此考虑通过若干个向量两两之间拼出若干 (0, x),根据裴蜀定理,只要满足 \displaystyle\gcd_{\forall (0, x)}(|x|) = 1 且有正有负即可。

下面讨论两种情况:

  1. 本来就是 (0, x) 的形式

直接加入集合即可。

  1. 本来是由 (p_i, q_i), (p_j, q_j) 拼起来

设向量 i 用了 x 次,向量 j 用了 y 次,则需要满足:

由于 x, y \geq 0,则此时必须满足 p_i, p_j 异号。

于是我们可以解出一组绝对值最小的解:

注意 x, y 的符号可能与上述恰好相反。

代入 q_i, q_j 即可得到当前构造出的向量 (0, \frac{q_i |p_j| + q_j |p_i|}{|\gcd(p_i, p_j)|})。

swap 一下 p, q 再做一遍即可。时间复杂度为 O(Tn^2 \log w),其中 w 为 p_i, q_i 的值域 100。

代码:

#include <iostream>
#include <cstdlib>

using namespace std;

int p[107], q[107], absp[107];

int gcd(int a, int b){
    return b == 0 ? a : gcd(b, a % b);
}

inline bool solve(int n){
    int d = 0;
    bool negative = false, positive = false;
    for (int i = 1; i <= n; i++){
        absp[i] = abs(p[i]);
        if (p[i] == 0){
            d = gcd(d, abs(q[i]));
            if (q[i] < 0){
                negative = true;
            } else if (q[i] > 0){
                positive = true;
            }
        }
    }
    for (int i = 1; i < n; i++){
        if (p[i] != 0){
            for (int j = i + 1; j <= n; j++){
                if (p[j] != 0){
                    int t = (p[i] * q[j] - p[j] * q[i]) / gcd(absp[i], absp[j]);
                    d = gcd(d, abs(t));
                    if ((p[i] > 0) != (p[j] > 0)){
                        if (p[i] < 0) t = -t;
                        if (t < 0){
                            negative = true;
                        } else if (t > 0){
                            positive = true;
                        }
                    }
                }
            }
        }
    }
    return negative && positive && d == 1;
}

int main(){
    int t;
    cin >> t;
    for (int i = 1; i <= t; i++){
        int n;
        cin >> n;
        for (int j = 1; j <= n; j++){
            cin >> p[j] >> q[j];
        }
        if (!solve(n)){
            cout << "NIE" << endl;
            continue;
        }
        swap(p, q);
        if (!solve(n)){
            cout << "NIE" << endl;
        } else {
            cout << "TAK" << endl;
        }
    }
    return 0;
}