羊、狼、农夫过河
题目描述
羊、狼、农夫都在岸边,当羊的数量小于狼的数量时,狼会攻击羊,农夫则会损失羊。农夫有一艘容量固定的船,能够承载固定数量的动物。
要求求出不损失羊情况下将全部羊和狼运到对岸需要的最小次数。只计算农夫去对岸的次数,回程时农夫不会运送羊和狼。
备注:农夫在或农夫离开后羊的数量大于狼的数量时狼不会攻击羊。
输入描述
第一行输入为M,N,X,分别代表羊的数量,狼的数量,小船的容量。
输出描述
输出不损失羊情况下将全部羊和狼运到对岸需要的最小次数(若无法满足条件则输出0)。
#include <iostream>
#include <string>
#include<vector>
#include <unordered_set>
// #include <stdio.h>
#include <algorithm>
// #include <unordered_map>
// #include<queue>
// #include<cmath>
// #include <sstream>
// #include <functional>
// #include <limits.h>
using namespace std;
int main(){
int M,N,X;
cin>>M>>N>>X;
int res=0;
if(M<=N){
cout<<0<<endl;
return 0;
}
int M1 = M-(X) , N1 = N-(X-1) , M2 = X , N2 = X-1;
if(M1==N1){
cout<<0<<endl;
return 0;
}else{
res=2;
}
while(M1>N1&&M2>N2&&M1>=X){
M1 = M1-X;
N1 = N1-X;
M2 = M2 +X;
N2 = N2 + X;
}
if(M1<=N1){
cout<<0<<endl;
return 0;
}
if(M1+N1<=X){
res++;
}else{
res++;
res++;
}
cout<<res<<endl;
}