将N跟香肠平均分成M份的最少切割刀数

来源:互联网 发布:java 监听器 编辑:程序博客网 时间:2024/04/29 13:23
1000. Cutting Sausages
soj.me
2014.3.1
 
    
Time Limit: 1sec    Memory Limit:256MB
Description
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. 
 
Input

The first and only line of input contains two positive integers, N and M (1 ≤ N, M ≤ 100), the number of sausages and tasters, respectively.

Output

The first and only line of output must contain the required minimum number of cuts.

Sample Input
 Copy sample input to clipboard
样例1:2 6样例2:3 4样例3:6 2
Sample Output
样例1:4样例2:3样例3:0

Problem Source: 2014年每周一赛第一场


分析:
   题目的意思就将N根香肠平均的分成M份,并且要求切割的次数最少,求最少的次数.
 1) 当N%M==0时,直接输出为0;
 2)当N > M时,没人将得到一根完整的香肠,在将剩下的N%M根香肠平均分成M份,所以,令N = N % M后,直接跳到第三步;
 3)当N < M时, 如果M%N==0, 则将每跟香肠切(M%N-1)刀; 否则,切(M%N)刀;
 4)将切割之后,每跟香肠剩下的一小部分再进行平均分配。这时,是将N小段香肠平均分成(M%N)份。(即M=M%N)
 5) 回到第一步进行循环,结束条件:当N是M的倍数时,结束循环,或者当M为0时,结束循环。

C代码:


#include<stdio.h>int main(){int N, M;scanf("%d%d",&N,&M);int ans = 0;while(N % M != 0)   // 当N是M的倍数时,结束循环{if(N > M)  N = N % M;int s = M%N == 0 ? M / N -1 : M / N;  //当N小于M时,将N跟香肠分成M份,需要切的刀数。M = M % N;ans = ans + s * N;if(M == 0)    //当M为0时,结束循环            break;}printf("%d\n",ans);}



   
0 0