acm练习题——计算最小金额

Description
描述

You are given two integers x and y. You can perform two types of operations:
给定两个整数x和y,可以执行两种操作:

Pay a dollars and increase or decrease any of these integers by 1. For example, if x=0 and y=7 there are four possible outcomes after this operation:
支付a美元,将这些整数增加或减少1。例如,如果x=0 y=7之后有四种可能的结果:
x = 0, y = 6;
x = 0, y = 8;
x = -1, y = 7;
x = 1, y = 7;

Pay b dollars and increase or decrease both integers by 1. For example, if x=0 and y=7 there are two possible outcomes after this operation:
支付b元,两个整数增加或减少1。例如,如果x=0, y=7,在此操作后有两种可能的结果:
x = -1, y = 6;
x = 1, y = 8;

Your goal is to make both given integers equal zero simultaneously, i.e. x=y=0. There are no other requirements. In particular, it is possible to move from x=1, y=0 to x=y=0.
你的目标是让给定的整数同时为0,即x=y=0。没有其他要求。特别地,它可以从x=1 y=0移动到x=y=0。

Calculate the minimum amount of dollars you have to spend on it.
计算你在这上面必须花费的最小金额。

Input

The first line of each test case contains two integers x and y (0≤x,y≤1000).
每个测试用例的第一行包含两个整数x和y(0≤x,y≤1000)。
The second line of each test case contains two integers a and b (1≤a,b≤1000).
每个测试用例的第二行包含两个整数a和b(1≤a,b≤1000)。

Output

For each test case print one integer — the minimum amount of dollars you have to spend.
对于每个测试用例,打印一个整数——您必须花费的最小金额。

Sample Input 1

1 3
391 555
Sample Output 1

1337
Sample Input 2

0 0
9 4
Sample Output 2

0

这道题呢,我的思路比较简单,就是分情况讨论:
1.当X=0且Y=0时直接输出0;
2.当X=0或Y=0时,我们只能将另一个不等于0的数组一直减为0才是最简支付金额,即最小金额=不等于0的数*a。
3.当X、Y均大于0时:
(1)a*2<=b时直接减就是最小金额。
(2)如果a*2>b就X、Y同时减1直到有一个为0,然后就将另一个减到0就可以了.
4.当X、Y均小于0时,原理同上。
5.当X、Y不同号时,最小金额就是直接X、Y单个加减为0就可以了。

#include<stdio.h>                
#include<math.h>
int main(void){
	int a,b,x,y,i,num;
	while(scanf("%d %d",&x,&y) != EOF){
		scanf("%d %d",&a,&b);
		num=0;
		if(x==0){                  
			num+=abs(y)*a;
			y=0;
		}
		if(y==0){
			num+=abs(x)*a;
			x=0;
		}
		if(x>0&&y>0){
			if(2*a<=b){
				num=a*x+a*y;
				x=0;
				y=0;
			}
			else{
				if(x>=y){
					num=y*b+(x-y)*a;
					x=0;
					y=0;
				}
				else{
					num=x*b+(y-x)*a;
					x=0;
					y=0;
				}
			}
		}
		if(x<0&&y<0){
			if(2*a<=b){
				num=a*-x+a*-y;
				x=0;
				y=0;
			}
			else{
				if(x>=y){
					num=-x*b+(x-y)*a;
					x=0;
					y=0;
				}
				else{
					num=-y*b+(y-x)*a;
					x=0;
					y=0;
				}
			}
		}
		if(x>0&&y<0||x<0&&y>0){
			num=abs(x-y)*a;
			x=0;
			y=0;
		}
		printf("%d\n",num);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值