【Codeforces 793 A. Oleg and shares】

来源:互联网 发布:超级搜索软件 编辑:程序博客网 时间:2024/06/05 12:03

A. Oleg and shares
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
Input
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second.
The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ 109) — the initial prices.
Output
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
Examples
Input
3 3
12 9 15
Output
3
Input
2 2
10 9
Output
-1
Input
4 1
1 1000000000 1000000000 1000000000
Output
2999999997
Note
Consider the first example.
Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.
There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.
In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.
In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.

1) 找出最小数

2)能否都变成最小数,需要多少秒

AC代码:

#include<cstdio>#include<algorithm>using namespace std;typedef long long LL;const int MAX = 1e5 + 10;int a[MAX];int main(){    int n,k,o = 1e9;    scanf("%d %d",&n,&k);    for(int i = 1; i <= n; i++)        scanf("%d",&a[i]),o = min(o,a[i]);    LL ok =  1,p = 0;    for(int i = 1; i <= n; i++){        int w = a[i] - o;        if(w < 0 || w % k)            ok = 0;        p += w / k;    }    if(ok)        printf("%lld\n",p);    else        puts("-1");    return 0;}
原创粉丝点击