CF2117D题解

· · 题解

洛谷·题目传送门

CF·题目传送门

题目分析

数学建模:

我们需要判断给定的数组是否可以通过一系列操作变为全零数组。每次操作有两种选择:

我们需要找到非负整数 x 和 y 满足所有 n 个方程。

解方程:

对于 i=1 和 i=n :

这是一个关于 \mathbf{x} 和 \mathbf{y} 的线性方程组:

x+n y=a_{1} \\ n x+y=a_{n} \end{array}\right.

算法步骤

对于每个测试用例:

计算 y = (n \times a_0 - a_{n-1}) {\div} (n^2 - 1) 和 x = (n \times a_{n-1} - a_0) {\div} (n^2 - 1)。

检查 x 和 y 是否为非负整数。

如果 x 或 y 为负数或非整数,直接返回不行。

否则,验证所有 a_i 是否满足 x \times (i+1) + y \times (n - i) = a_i。

如果所有验证通过,返回可以;否则返回不行。

代码如下

#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<int> a(n);
        for (int i = 0; i < n; ++i) cin >> a[i];    
        if (n == 1) {
            cout << (a[0] == 0 ? "YES" : "NO") << endl;
            continue;
        }
        int a1 = a[0],an = a[n-1],D = (int)n * n - 1,ny = n * a1 - an;
        if (ny % D != 0) {
            cout << "NO" << endl;
            continue;
        }
        int y = ny / D,nx = a1 - n * y;
        if (nx < 0 || (a1 - n * y) != nx) {
            cout << "NO" << endl;
            continue;
        }
        int x = nx;
        if (x < 0 || y < 0) {
            cout << "NO" << endl;
            continue;
        }
        bool V = true;
        for (int i = 1; i <= n; ++i) {
            int exp = x * i + y * (n - i + 1);
            if (exp != a[i-1]) {
                V = false;
                break;
            }
        }
        cout << (V ? "YES" : "NO") << endl;
    }
    return 0;
}

通过记录

下期见!拜拜!