题意:
有n棵树,其魔力值为ai,对于任意(i, j) (i可以等于j),将出现魔力值为$a_i - a_j$ 和 $a_i$ + $a_j$ 的树在森林中,想知道是否有魔力值为x的树在森林中。
思路:
n个整数的裴蜀定理
有$a_1x_1+a_2x_2+...+a_nx_n = gcd(a_1, a_2, ..., a_n) = d$
若$x % d == 0$,则有解(求n元一次方程),否则无解
Code:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; const int N = 1e3 + 20; int n, m; ll a[N], ans[N]; ll exgcd(ll a, ll b, ll &x, ll &y){ if(!b){ x = 1, y = 0; return a; } ll d = exgcd(b, a % b, y, x); y -= a / b * x; return d; } int main(){ cin >> n >> m; for(int i = 0; i < n; i ++){ cin >> a[i]; } ll g = a[0]; ans[0] = 1; ll k; for(int i = 1; i < n; i ++){ g = exgcd(g, a[i], k, ans[i]); for(int j = 0; j < i; j ++){ ans[j] *= k; } } int x; while(m --){ cin >> x; if(x % g == 0){ k = x / g; for(int i = 0; i < n; i ++){ cout << ans[i] * k << " "; } cout << endl; } else{ puts("NO"); } } return 0; }