E. G-C-D, Unlucky!

https://codeforces.com/problemset/problem/2126/E

题意:给定一个未知数组a的前缀和后缀gcd数组p和s,问这样的数组a是否存在,输出yes或者no。

思路:考虑a中的每一个位置i,gcd(a[i], s[i - 1]) == g1, gcd(a[i], p[i + 1]) == g2, 那么a[i]必定包含lcm(g1, g2),这样才能满足条件,根据此逻辑,求出所有的a,然后做一次运算,看能否得到p和s即可。

inline void solve() {
    int n;
    cin >> n;

    vector<int> p(n), s(n);
    for (auto& x : p) {
        cin >> x;
    }

    for (auto& x : s) {
        cin >> x;
    }

    if (p[n - 1] != s[0]) {
        cout <<"NO\n";
        return;
    }

    auto valid = [](const std::vector<int>& a) {
        int n = (int)a.size();
        for (int i = 0; i < n - 1; ++i) {
            if (a[i] % a[i + 1] != 0) {
                return false;
            }
        }
        return true;
    };

    reverse(s.begin(), s.end());
    if (!valid(p) || !valid(s)) {
        cout <<"NO\n";
        return;
    }

    reverse(s.begin(), s.end());
    vector<long long> a(n);

    a[0] = p[0];
    a[n - 1] = s[n - 1];
    for (int i = 1; i < n - 1; ++i) {
        a[i] = ::lcm(p[i], s[i]);
    }

    long long g = 0;
    for (int i = 0; i < n; ++i) {
        g = ::gcd(g, a[i]);
        if (g != p[i]) {
            cout << "No\n";
            return;
        }
    }

    g = 0;
    for (int i = n - 1;i >= 0; --i) {
        g = ::gcd(g, a[i]);
        if (g != s[i]) {
            cout << "NO\n";
            return;
        }
    }

    cout << "Yes\n";
}
posted @ 2025-11-14 09:56  _Yxc  阅读(5)  评论(0)    收藏  举报