【codeforces 793A】Oleg and shares

【题目链接】:http://codeforces.com/contest/793/problem/A

【题意】

每次你可以对1..n中的任意一个数字进行减少k操作;
问你最后可不可能所有的数字都变成一样的;
可能的话输出最小操作次数;

【题解】

a[x1]-k*x1=t
a[x2]-k*x2=t
x1是对a[x1]的操作次数..以此类推
则有
a[x1]-a[x2]=k*(x2-x1)
可知a[x1]-a[x2]必然为k的倍数否则无解;
则升序排;
相邻两个数字的差必然要求为k的倍数;
即%k==0
然后全都变成最小的那个数显然是最优的.

【Number Of WA

0

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 1e5+100;

LL n,k;
LL a[N];

int main()
{
    //freopen("F:\rush.txt","r",stdin);
    ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
    cin >> n >> k;
    rep1(i,1,n) cin >> a[i];
    sort(a+1,a+1+n);
    rep1(i,1,n-1)
    {
        LL t = a[i+1]-a[i];
        if (t%k!=0)
            return cout << -1 << endl,0;
    }
    LL ans = 0;
    rep1(i,1,n)
    {
        LL temp = a[i]-a[1];
        ans+=(temp/k);
    }
    cout << ans << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626385.html