AtCoder Beginner Contest 207 B题
B - Hydrate
Time Limit: 2 sec / Memory Limit: 1024 MB
Score :
200 points
Problem Statement
There is a container with
A cyan balls. Takahashi will do the following operation as many times as he likes (possibly zero times):
add B cyan balls and C red balls into the container.
Takahashi’s objective is to reach a situation where the number of cyan balls in the container is at most
D times the number of red balls in it.
Determine whether the objective is achievable. If it is achievable, find the minimum number of operations needed to achieve it.
Constraints
1≤A,B,C,D≤105
All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B C D
Output
If Takahashi’s objective is achievable, print the minimum number of operations needed to achieve it. Otherwise, print -1.
Sample Input 1
Copy
5 2 3 2
Sample Output 1
2
先解释一下题目:有一个放a个青球的容器,我一次放b个青球和c个红球,我需要放几次才能使红球个数的d倍大于青球的个数,如果不可能大于,则输出-1;
那么首先,当b>=c*d时,不管放几次红球个数的d倍都不可能大于青球的个数。所以代码为
if(b>=c*d) cout<<"-1";
然后,如果可行,因为数据不大,所以直接循环就可以,所以代码为
long long int a,b,c,d,num=0,C=0;//不用long long会爆;声明一个C用来算c累加的值
cin>>a>>b>>c>>d;
if(b>=c*d){
cout<<-1;
return 0;
}
while(a>C*d){
a+=b;
C+=c;
num++;
}
cout<<num;
return 0;
但是,同样还有个更简单的办法,计算cd-b的差值n,然后当差值nd>a时,计算次数
n=c*d-b;//n用来存放差值
while(a>0){
num++;
a-=n;
cout<<num;
}
也有个更快的,可以算a/n向上取整的值
//记住是double声明的,要不然会自动四舍五入
n=c*d-b;
num=ceil(a/n);//ceil()为向上取整函数
cout<<num;