题解:CF2117D Retaliation

· · 题解

题意:

有一个序列 a,能不能让所有元素均为 0,可以执行以下操作任意次:

  1. 对 a 中所有的下标 i,令 a_i 自减 i。
  2. 对 a 中所有的下标 i,令 a_i 自减 n-i+1。

解法:

设操作 1 执行 x 次,操作 2 执行 y 次。

对每个元素 a_i 需满足:

a_i=x \times i + y \times (n-i+1)

因 x 和 y 是全局统一值,则直接用前两个元素联立方程组:

a_1=x + n \times y\\ a_2=2 \times x + (n-1)\times y\\ \end{cases}

解得:

x = \frac{n \cdot a_2 - (n-1) \cdot a_1}{n+1} y = \frac{2a_1 - a_2}{n+1}

:::success[AC Code]

#include<bits/stdc++.h>
using namespace std;
using ll=long long;
void solve(){
    int n;
    cin>>n;
    vector<ll>a(n+1);
    for(int i=1;i<=n;i++)cin>>a[i];
    ll num=2*a[1]-a[2];
    ll den=n+1;
    if(num%den!=0){
        cout<<"NO\n";
        return;
    }
    ll y=num/den;
    ll x=a[1]-n*y;
    if(x<0||y<0){
        cout<<"NO\n";
        return;
    }
    for(int i=1;i<=n;i++){
        ll exp=x*i+y*(n-i+1);
        if(a[i]!=exp){
            cout<<"NO\n";
            return;
        }
    }
    cout<<"YES\n";
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin>>t;
    while(t--)solve();
    return 0;
}