All are Same 思维,gcd

在这里插入图片描述
题意 :

  • 给一序列,每次可以选一个数减去k(k>=1),求最大的k能够使得在若干次操作后序列每个元素相等,若k为任意大则输出-1

思路 :

  • 假设最小数为mi,那么显然最终所有数都为mi
  • 因此,答案就是求所有元素与mi之差的gcd
  • 特别地,当所有元素初始相等,则k可以是任意大,gcd结果会是0,则输出-1
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>
#include <unordered_set>
#include <set>
#include <vector>
 
using namespace std;

typedef long long ll;

const int N = 55;

int a[N];

int gcd(int a, int b)
{
    return b ? gcd(b, a % b) : a;
}

int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    
    int _;
    cin >> _;

    while (_ -- )
    {
        int n;
        cin >> n;
        
        int mi = 1e9;
        for (int i = 1; i <= n; i ++ ) cin >> a[i], mi = min(mi, a[i]);
        
        int ans = 0;
        for (int i = 1; i <= n; i ++ ) ans = gcd(ans, a[i] - mi);
        
        if (ans == 0) cout << -1 << endl;
        else cout << ans << endl;
    }
    
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值