题解:CF763C Timofey and remoduling

· · 题解

我当时想了一个很好玩的做法。差不多想写了 40\min 就可以做出来。

我们设 S=\sum a_i,然后考虑用 x,d 构造出等差数列: x,x+d,x+2d,\cdots,x+(n-1)d,和直接用数学算出来是

\sum_{i=0}^{n-1} x+id = nx+\dfrac{n(n-1)}{2}d

然后联立两个方程得到一个方程组

\begin{cases}S=\sum a_i \\ S=nx+\dfrac{n(n-1)}{2}d\end{cases}

因为用 1 是 S 是用常数数组 a 决定的,而 2 一共涉及两个未知数,而合法 x 的值域显然是 a 的子集,所以 x 一共有 \mathcal{O(n)} 个,x 和 d 是一一对应的,所以对于每个 x 直接找到 d 然后随机一个检查顺序就能过了。

#include <bits/stdc++.h>
#define gz(x) (x%MOD)
using ll = long long;
using namespace std;
int tt;
namespace wangcy{
    const int N=1e5+10;
    ll S,n,MOD,a[N],p[N];
    inline ll qpow(ll st,ll b=MOD-2){
        ll r=1;
        while(b){
            if(b&1)r=r*st%MOD;
            st=st*st%MOD, b>>=1;
        }
        return r;
    }
    unordered_map<ll,int>t;
    inline bool judge(ll x,ll d){
        for(int i=0;i<n;++i){
            ll ind=(x+p[i]*d)%MOD;
            t[ind]--;
            if(t[ind]<0){
                for(int k=0;k<=i;++k)t[(x+p[k]*d)%MOD]++;
                return false;
            }
        }
        return cout<<x<<" "<<d<<"\n",true;
    }
  inline void Main(){
    srand(time(0)),t.clear(),S=0;
    cin>>MOD>>n;
    for(int i=1;i<=n;++i)cin>>a[i],S+=a[i],S%=MOD,++t[a[i]],p[i-1]=i-1;
    random_shuffle(p,p+n);
    ll x=0,d=0;
    for(int i=n;i;--i){
        x=a[i];
      d=2ll*(S-n*x%MOD)%MOD*qpow(n*(n-1)%MOD)%MOD;
      d=(d%MOD+MOD)%MOD;
      if(judge(x,d))return void();
        }
        return cout<<"-1\n",void();
    }
}
int main(){
    freopen("diff.in","r",stdin),freopen("diff.out","w",stdout);
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>tt;
    while(tt--)wangcy::Main();
    return 0;
}