2021-08-27

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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值