一个人要从一条河的A岸到B岸,他带这,一头狼,一只羊,还有一筐白菜,可是过河的船只能让每次只能让他带这一样东西过河,可是如果,人不在的时候,狼会吃掉羊,羊会吃掉白菜,
可以根据以下步骤编一个程序,让人可以顺利的过河,并且又不损失任何东西,
1,人先带着羊过河,
2,人空手回来,
3,人带着狼过河,
4,人带着羊回来,
5,人带着白菜过河,
6,人空手回来,
7,人带着羊过河
这个问题我前两天发过,可是因为数据库的问题,把我的帖子删了,希望大家能帮帮忙!
// 由于时间的关系,程序没有帮你完全写完,希望有兴趣的朋友把它补充完整
#include <cstdlib> #include <iostream> #include <stdio.h>
using namespace std;
struct Side { char name[50]; int man; int sheep; int wolf; int greens; int situation; int newSituation; void update() { man = situation & 0x8; sheep = situation & 0x4; wolf = situation & 0x2; greens = situation & 0x1; } Side(int s, const char * pn) { strcpy(name, pn); situation = s; update(); } bool check_ok() { int sitation = man | sheep | wolf | greens; bool result = true; for(int i = 5; i<=10; i++) { if(i == sitation) { result = false; break; } } return result; } void report() { // add your code // for example: // *** moved, ***moved } bool move(Side * anotherSide) { bool move; switch(situation) { case 15: situation = 3; anotherSide->situation = 12; update(); anotherSide->update(); report(); anotherSide->report(); move = true; break; case 14:
break;
} return move; } };
int main() { Side SideA(15, "SideA"); Side SideB(0, "SideB");
while(SideA.situation != 0) { if(SideA.move(&SideB)) ; else SideB.move(&SideA); }
system("pause"); return 0; }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <windows.h> #define WOLF 3 //狼 #define SHEEP 2 //羊 #define CABBAGE 1 //白菜 int a[3]={WOLF,SHEEP,CABBAGE},b[3]; //A岸,B岸 int count_a=3,count_b=0; //未过河数,过河数 int main() { int i; //循环变量 printf("A岸的初始状态:\t"); for(i=0;i<count_a;i++) printf("%d\t",a[i]); printf("\n"); int state=0; //往返状态,0为A去往B;1为B返回A while(1) { switch(state) { case 0: //A去往B if(count_a==3) while(1) { int t=abs(a[0]-a[1]); if(t==1) { t=a[0]; a[0]=a[1]; a[1]=a[2]; a[2]=t; for(i=0;i<count_a;i++) printf("%d\t",a[i]); printf("\n"); continue; } else { b[count_b++]=a[--count_a]; printf("\n过河:%d\n",b[count_b-1]); printf("过河后A岸的状态:\t"); for(i=0;i<count_a;i++) printf("%d\t",a[i]); printf("\n\n"); break; } } else if(count_a==2) { int t=a[0]; a[0]=a[1]; a[1]=t; b[count_b++]=a[--count_a]; printf("过河:%d\n",b[count_b-1]); printf("过河后A岸的状态:\t"); for(i=0;i<count_a;i++) printf("%d\t",a[i]); printf("\n\n"); } else { b[count_b++]=a[--count_a]; printf("过河:%d\n",b[count_b-1]); printf("过河后A岸的状态:\t"); for(i=0;i<count_a;i++) printf("%d\t",a[i]); printf("\n\n"); } state++; system("pause"); break; case 1: //B返回A if(count_b==1) { printf("返回:人\n返回后的状态:\t"); for(i=0;i<count_b;i++) printf("%d",b[i]); printf("\n\n"); } else if(count_b==2) { int t=abs(b[0]-b[1]); if(t==1) { t=b[0]; b[0]=b[1]; b[1]=t; a[count_a++]=b[--count_b]; printf("返回:%d\n",a[count_a-1]); } else printf("返回:人\n"); printf("返回后的B岸的状态:\t"); for(i=0;i<count_b;i++) printf("%d\t",b[i]); printf("\n\n"); } state--; system("pause"); break; } if(count_b==3) break; } printf("成功过河!"); return 0; }