Codeforces CF1459C. Row GCD C++ GCD分配率

C. Row GCD

time limit per test2 seconds
memory limit per test512 megabytes
inputstandard input
outputstandard output
You are given two positive integer sequences a1,…,an and b1,…,bm. For each j=1,…,m find the greatest common divisor of a1+bj,…,an+bj.

Input
The first line contains two integers n and m (1≤n,m≤2⋅105).

The second line contains n integers a1,…,an (1≤ai≤1018).

The third line contains m integers b1,…,bm (1≤bj≤1018).

Output
Print m integers. The j-th of them should be equal to GCD(a1+bj,…,an+bj).

Example
inputCopy

4 4
1 25 121 169
1 2 7 23

outputCopy

2 3 8 24


分析
思路:根据最大公约数的分配律,gcd(a,b,c) = gcd(a,b-a,c-b);
那么对于数列来说,gcd(a1, a2, a3, a4…) = gcd(a1, a2-a1, a3-a2, a4-a3…)
所有a[]数字加上bj后,等价变形发现答案为GCD(a1+bj,a2-a1, a3-a2, a4-a3…),
只需要先求出数组a[]的最大公约数g,之后求出GCD(a1+bj,g)即可。

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 2e5 + 10;
ll a[N], b[N];
ll gcd(ll a,ll b)
{
    
    
	return b?gcd(b,a%b):a;
}
int main() {
    
    
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) cin >> a[i];
    for (int i = 1; i <= m; ++i) cin >> b[i];

    ll g = 0;
    for (int i = 2; i <=n; ++i) {
    
    
        g = gcd(g, a[i] - a[i - 1]);
	}

    for (int i = 1; i <=m; ++i) {
    
    
        cout << abs(gcd(a[1] + b[i], g)) << " ";
    }
    puts("");

    return 0;
}



猜你喜欢

转载自blog.csdn.net/Jay_fearless/article/details/111415526