ZOJ 1005 || POJ 1606

来源:互联网 发布:音乐相册制作软件app 编辑:程序博客网 时间:2024/06/03 21:53

   看了别人的代码。发现ZOJ的那个用数学解法挺简单的诶!!不过POJ的那个题有提到最少次数~所以我还是规规矩矩用广搜写了~人生中第二次写广搜,昨天研究了半天,最后才自己写出来尴尬

#include <climits>#include <cstring>#include <iostream>#include <memory>#include <queue>#include <stack>using namespace std;typedef struct node {  int a, b, flag, step;  node *pre;} Node;int visit[117][117];int A, B, N, ans;Node temp, arr_node[317];stack<int> S;queue<Node> Q;void BFS(int x, int y) {  visit[x][y] = 1;  int count = -1;  temp.a = 0;  temp.b = 0;  temp.step = 0;  temp.pre = NULL;  temp.flag = 0;  Q.push(temp);  while (!Q.empty()) {    count++;    arr_node[count] = Q.front();    Q.pop();    for (int i = 1; i <= 6; i++) {      switch (i) {      case 1:        temp.a = A;        temp.b = arr_node[count].b;        temp.flag = 1;        break;      case 2:        temp.b = B;        temp.a = arr_node[count].a;        temp.flag = 2;        break;      case 3:        temp.a = 0;        temp.b = arr_node[count].b;        temp.flag = 3;        break;      case 4:        temp.a = arr_node[count].a;        temp.b = 0;        temp.flag = 4;        break;      case 5:        temp.a = (arr_node[count].a < B - arr_node[count].b)                     ? 0                     : (arr_node[count].a + arr_node[count].b - B);        temp.b = (arr_node[count].a < B - arr_node[count].b)                     ? (arr_node[count].a + arr_node[count].b)                     : B;        temp.flag = 5;        break;      case 6:        temp.b = (arr_node[count].b < A - arr_node[count].a)                     ? 0                     : (arr_node[count].a + arr_node[count].b - A);        temp.a = (arr_node[count].b < A - arr_node[count].a)                     ? (arr_node[count].a + arr_node[count].b)                     : A;        temp.flag = 6;        break;      }      if (visit[temp.a][temp.b])        continue;      visit[temp.a][temp.b] = 1;      temp.pre = &arr_node[count];      if (temp.a == N || temp.b == N) {        while (temp.pre) {          S.push(temp.flag);          temp = *temp.pre;        }        return;      }      Q.push(temp);    }  }}void print() {  while (!S.empty()) {    int i = S.top();    S.pop();    switch (i) {    case 1:      cout << "fill A" << endl;      break;    case 2:      cout << "fill B" << endl;      break;    case 3:      cout << "empty A" << endl;      break;    case 4:      cout << "empty B" << endl;      break;    case 5:      cout << "pour A B" << endl;      break;    case 6:      cout << "pour B A" << endl;      break;    }  }  cout << "success" << endl;}int main(void) {  while (cin >> A >> B >> N) {    while (!Q.empty())      Q.pop();    while (!S.empty())      S.pop();    memset(visit, 0, sizeof(visit));    BFS(0, 0);    print();  }  return 0;}