思维题-CodeForces 371B Fox Dividing Cheese

88 篇文章 0 订阅
86 篇文章 0 订阅

题意:

给出a,b。问a和b经过最少几步的 /2  /3 /5变化可以相等。

看完官方题解才明白

官方题解
It is easy to see that the fox can do three type of operations: divide by 2, divide by 3 and divide by 5. 
Let’s write both given numbers in form a = x·2a2·3a3·5a5, b = y·2b2·3b3·5b5, where x and y are not dibisible by 2, 3 and 5.
 If x ≠ y the fox can’t make numbers equal and program should print -1. If x = y then soluion exists.
 The answer equals to |a2 - b2| + |a3 - b3| + |a5 - b5|, because |a2 - b2| is the minimal number of operations to have 2 in the same power in both numbers, 
|a3 - b3| is the minimal number of operations to have 3 in the same power in both numbers, and |a5 - b5| is the same for 5.

整体思路:

如果a,b经过所有的 /2 /3 /5操作后,数值不等,那么一定无法通过变化得到。

反之,如果最后相等了,那必定有解。那么2  3 5 操作的差值就是解

代码while循环写多了。可以封装函数

#include<iostream>
#include <math.h>
using namespace std;

int main()
{
    int a,b;
	while(cin>>a>>b){
    int a2=0,a3=0,a5=0;
    int b2=0,b3=0,b5=0;
 	while(a%2==0)
    {
        a=a/2;
        a2++;
    }
    while(b%2==0)
    {
        b=b/2;
        b2++;
    }
    while(a%3==0)
    {
        a=a/3;
        a3++;
    }
    while(b%3==0)
    {
        b=b/3;
        b3++;
    }
    while(a%5==0)
    {
        a=a/5;
        a5++;
    }
    while(b%5==0)
    {
        b=b/5;
        b5++;
    }
    if(a!=b)
        cout<<-1<<endl;
    else
        cout<<fabs(a2-b2)+fabs(a3-b3)+fabs(a5-b5)<<endl;
 	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值