#include <vector>
#include <iterator>
using namespace std;
struct stateVariable //状态变量,描述河的两边的商人数、随从数
int numOfSalesmen;
int numOfServant;
};
struct decisionVariable //决策变量,描述第k次过河船上的商人数、随从数
{
int numOfSalesmen;
int numOfServant;
};
stateVariable startState={3,3}; //初始状态,原岸有三个商人、三个随从
decisionVariable decision1[]={{0,2},{1,1},{2,0}}; //从原来的岸边到对岸决策向量集合
//从河的对岸到原岸决策向量集合
decisionVariable decision2[]={{1,0},{0,1},{1,1},{0,2},{2,0}};
/**打印解,即打印每次的决策向量*/
void PrintSolve(vector<decisionVariable> slove)
{
int i;
for(i=0;i<slove.size();i++)
{
cout<<i+1<<":";
cout<<"("<<slove[i].numOfSalesmen<<",";
cout<<slove[i].numOfServant<<")"<<endl;
}
}
/**判断河的两边状态是否合法*/
bool judge(stateVariable oneSide,stateVariable anotherSide)
{
if( oneSide.numOfSalesmen<0 || oneSide.numOfSalesmen>3 ||
anotherSide.numOfSalesmen<0 || anotherSide.numOfServant>3 )
return false;
if( oneSide.numOfSalesmen!=0 && oneSide.numOfSalesmen<oneSide.numOfServant)
return false;
if( anotherSide.numOfSalesmen!=0 &&
anotherSide.numOfSalesmen<anotherSide.numOfServant)
return false;
return true;
}
/**递归求解商人过河
k表示第k步,当k为基数时,表示从原岸到对岸;当k为偶数时,表示从对岸回到原岸
currentState表示原岸的状态,即原岸的商人数和随从数
slove把第k次符合条件的决策向量保存
prev表示上一次决策向量
*/
void salesCrossRiver(int k,stateVariable currentState,
vector<decisionVariable> slove,decisionVariable prev)
{
int sign,i;
stateVariable tempState,anotherSide;
static int numOfSolve=0; //所以解决方案的个数
//递归出口,所以的商人和随从都到了对岸
if(currentState.numOfSalesmen==0 && currentState.numOfServant==0)
{
cout<<++numOfSolve<<":"<<endl;
PrintSolve(slove);
cout<<endl;
}
else
{
sign=(k%2==0?1:-1);
if(sign==-1) //从原岸到对岸
{
for(i=0;i<3;i++)
if(prev.numOfSalesmen!=decision1[i].numOfSalesmen || //不能跟上一次相同
prev.numOfServant!=decision1[i].numOfServant)
{
tempState.numOfSalesmen
=currentState.numOfSalesmen+sign*decision1[i].numOfSalesmen;
tempState.numOfServant
=currentState.numOfServant+sign*decision1[i].numOfServant;
anotherSide.numOfSalesmen
=startState.numOfSalesmen-tempState.numOfSalesmen;
anotherSide.numOfServant
=startState.numOfServant-tempState.numOfServant;
if(judge(tempState,anotherSide))
{
slove.push_back(decision1[i]);
salesCrossRiver(k+1,tempState,slove,decision1[i]);
solve.pop_back();
}
}
else
{
for(i=0;i<5;i++)
if(prev.numOfSalesmen!=decision1[i].numOfSalesmen || //不能跟上一次相同
prev.numOfServant!=decision1[i].numOfServant)
{
tempState.numOfSalesmen
=currentState.numOfSalesmen+sign*decision2[i].numOfSalesmen;
anotherSide.numOfSalesmen
=startState.numOfSalesmen-tempState.numOfSalesmen;
anotherSide.numOfSalesmen=startState.numOfSalesmen-tempState.numOfSalesmen;
anotherSide.numOfServant=startState.numOfServant-tempState.numOfServant;
if(judge(tempState,anotherSide))
{
slove.push_back(decision2[i]);
salesCrossRiver(k+1,tempState,slove,decision2[i]);
vector<decisionVariable>::iterator iter=slove.end()-1; //回到原来状态??
slove.erase(iter);
}
}
}
}
}
int main()
{
vector<decisionVariable> slove;
decisionVariable prev;
prev.numOfSalesmen=0;
prev.numOfServant=0;
salesCrossRiver(1,startState,slove,prev);
return 0;
}