用代码实现一道小学题
猎人带着狼、羊、菜过河,一次只能带一样乘船过河,只有猎人能划船,猎人不在的时候狼会吃羊,羊会吃菜,问怎么把狼、羊、菜带过河。
[解决办法]
算法如下:
#include <iostream.h>#include <stdlib.h>#define WOLF 0x4#define SHEEP 0x2#define VEGETABLE 0x1bool SafeCheck(int nBaggage){ if ( (nBaggage & WOLF) && (nBaggage & SHEEP) ) return false; if ( (nBaggage & SHEEP) && (nBaggage & VEGETABLE) ) return false; return true;}char* GetBaggageName(int nBaggage){ if (nBaggage & WOLF) return "Wolf"; if (nBaggage & SHEEP) return "Sheep"; if (nBaggage & VEGETABLE) return "Vegetable"; return "";}void main(){ int nCount = 3; int nBaggage = 0; nBaggage |= WOLF; nBaggage |= SHEEP; nBaggage |= VEGETABLE; for (int i=0; i<nCount; i++) { int nOneBaggage = 0x1 << i; if ( SafeCheck(nBaggage ^ nOneBaggage) ) { cout << "first carry " << GetBaggageName(nOneBaggage) << " cross the river" << endl; } } system("pause");}
[解决办法]