Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox, how are you going to do that?", the curious bears asked. "It's easy", said the fox. "If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal".
The little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal.
The first line contains two space-separated integers a and b (1 ≤ a, b ≤ 109).
If the fox is lying to the little bears and it is impossible to make the pieces equal, print -1. Otherwise, print the required minimum number of operations. If the pieces of the cheese are initially equal, the required number is 0.
15 20
3
14 8
-1
6 6
0
题目链接:http://codeforces.com/contest/371/problem/B
题目的意思是给你两个数a,b,这两个数可以除以1/2,1/3,1/5,问最少变换多少次才能使两个数相等。
我猜的和gcd有关,没想到还真的有关系。
我们来看第一组示例,15=3*5,20=2*2*5,去掉公因数5,还剩下3个数,输出3即可,不能被2,3,5整除的输出-1.
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int c[4],d[4];
int main(){
int a,b;
scanf("%d%d",&a,&b);
if(a==b){
printf("0\n");
return 0;
}
int gcd=__gcd(a,b);
a/=gcd;
b/=gcd;
while(a%2==0){
a/=2;
c[0]++;
}
while(a%3==0){
a/=3;
c[1]++;
}
while(a%5==0){
a/=5;
c[2]++;
}
while(b%2==0){
b/=2;
d[0]++;
}
while(b%3==0){
b/=3;
d[1]++;
}
while(b%5==0){
b/=5;
d[2]++;
}
if(a!=b){
printf("-1\n");
return 0;
}
//for(int i=0;i<3;i++){
// printf("%d %d\n",c[i],d[i]);
//}
int ans=0;
for(int i=0;i<3;i++){
ans+=c[i];
ans+=d[i];
}
printf("%d\n",ans);
}
所谓神题必有神解,回滚做法 http://blog.youkuaiyun.com/synapse7/article/details/21085153

解析Codeforces B.FoxDividingCheese问题,通过计算两块奶酪重量的公约数来确定最少操作次数,使重量相等。涉及算法包括求最大公约数(GCD)及迭代去除可除因子。
2359

被折叠的 条评论
为什么被折叠?



