Oleg and shares (Codeforces
来源:互联网 发布:商业机构域名 编辑:程序博客网 时间:2024/05/17 10:40
题目链接:
http://codeforces.com/problemset/problem/793/A
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?
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.
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
3 312 9 15
3
2 210 9
-1
4 11 1000000000 1000000000 1000000000
2999999997
输入n、k,然后输入n个数。这n个数中每秒钟有一个数减少k,题目要求计算最少经过几秒钟后,这n个数都相等,如果不存在,那么输出-1 。注意:每秒钟只有一个数减少k。
解题思路:
经过思考会发现,如果存在的话,那么最终结果肯定是 n个数 都等于 最初最小的那个数 。那么先计算出最初最小的那个数,然后计算由剩下的n-1个数变为最小的那个数需要几秒钟即可。如果不存在的话,输出-1.
代码:
#include<iostream>#include<algorithm>using namespace std;int main(){ long long int a[100005],sum,k,z,n; //sum存储需要的秒数,z只是中间变量 double q; //q用于进行强制转换,判断能不能被整除 while(cin>>n>>k) { sum=0; z=1; for(int i=0;i<=n-1;i++) cin>>a[i]; sort(a,a+n); //计算最小的那个数,计a[0] for(int i=1;i<=n-1;i++) { q=(double)(a[i]-a[0])/k; //把整型转化成浮点型,判断能不能整除,如果不能整除,说明不存在 if(q==((a[i]-a[0])/k)) //如果存在,那么把该数字变成最小的那个数 所要经过秒数 加在sum上 sum=sum+(a[i]-a[0])/k; else //否则没说明不能被整除,说明该数字无法变为最小的数字,把z标记为0 { z=0; break; } } if(z==0) cout<<-1<<endl; else cout<<sum<<endl; } return 0;}
- Oleg and shares CodeForces
- Oleg and shares (Codeforces
- Oleg and shares CodeForces
- Codeforces 793A Oleg and shares 题解
- codeforces 793A Oleg and shares
- 【Codeforces 793 A. Oleg and shares】
- A. Oleg and shares
- CF-Tinkoff Challenge-Elimination Round-A-Oleg and shares
- Codeforces Round #380A - Interview with Oleg
- CodeForces 738A - Interview with Oleg(水题)
- codeforces 738A Interview with Oleg
- 【57.97%】【codeforces Round #380A】Interview with Oleg
- codeforces - 738A - Interview with Oleg(字符串处理)
- Codeforces 729A Interview with Oleg 简单暴力
- [ 线段树 网络流 ] Codeforces793G Oleg and chess
- Mount Windows (CIFS) LAN Shares and Overcome Libreoffice/.doc Issues
- Codeforces #380(Div.2)A.Interview with Oleg【模拟】水题
- A. Interview with Oleg
- 多线程操作说明
- CF449C Jzzhu and Apples (筛素数 数论
- JS导航
- BaseServlet
- 酒.污水效应
- Oleg and shares (Codeforces
- ThreadLocal详解
- ubuntu16 安装文本对比软件
- 友员函数 operator
- 02 MapReduce
- MySQL server5.7版出现server failed
- IMMEDIATE DECODABILITY POJ
- 自适应网站怎么做好些?
- 如何用C++递归在BST(Binary Search Tree) 数有几个节点大于根节点的数字