原题链接:Link
前言
一眼看到这题感觉没爬完,然后编者就去 SPOJ 看了一眼,发现确实没爬完 ...
题意简述
给你 \(n\) 个香肠,有 \(m\) 位品尝者,你要切多少刀才能让每位品尝者都吃到同样分量的香肠。输出切多少刀。
附上英文完整题面,由于编者被禁言了,希望管理员在审核的时候加上。
Mirko has given up on the difficult coach job and switched to food tasting instead. Having skipped
breakfast like a professional connoisseur, he is visiting a Croatian cured meat festival. The most
renowned cook at the festival, Marijan Bajs, has prepared N equal sausages which need to be
distributed to M tasters such that each taster gets a precisely equal amount. He will use his trusted knife
to cut them into pieces.
In order to elegantly divide the sausages, the number of cuts splitting individual sausages must be as
small as possible. For instance, if there are two sausages and six tasters (the first test case below), it is
sufficient to split each sausage into three equal parts, making a total of four cuts. On the other hand, if
there are three sausages and four tasters (the second test case below), one possibility is cutting off three
quarters of each sausage. Those larger parts will each go to one of the tasrers, while the fourth taster
will get the three smaller pieces (quarters) left over.
Mirko wants to try the famous sausages, so he volunteered to help Bajs. Help them calculate the
minimum total number of cuts needed to carry out the desired division.
以及补上一组 SPOJ 上有的样例:
Input:
3 4
Output:
3
解题思路
编者想到的是递归,分两种不同的情况。我命名递归函数为 \(rec\)
-
当 \(n>=m\) 时,递归 \(rec(n\) \(mod\) \(m)\)
-
当 \(n<m\) 时,递归 \(x+rec(n,m-n)\)
特别的,当 \(n\) 和 \(m\) 不互质时,我们取其最大公约数,设为 \(t\) ,递归 \(t*rec(n/t,m/t)\)
小提醒:当 \(x=0\) 与 \(x=1\) 时注意特判一下。
具体这样,可能有一点难度,想通了就好了,可手动模拟帮助理解。
实现看代码。
代码
#include<bits/stdc++.h>
using namespace std;
int rec(int x,int y){
int t;
if(x==0) return 0;
if(x==1) return y-1; //注意一下这两种情况的特判
t=__gcd(x,y); //直接使用 __gcd 函数,因为我用了万能头,要单独使用需加上头文件 algorithm 。如果想要速度更快可以手打。
if(t>1) return t*rec(x/t,y/t);
if(x>=y) return rec(x%y,y);
if(x<y) return x+rec(x,y-x); //三种情况递归
}
int main(){
int n,m;
cin>>n>>m;
int ans=rec(n,m);
cout<<ans;
return 0; //主函数按题意输入输出
}
结尾
具体就是这样,还有不懂可以私信我。
管理员审核辛苦了。
来源:oschina
链接:https://my.oschina.net/u/4313158/blog/3230740