……好久没写C了,好麻烦啊,在C++的环境下想尽可能地写得跟C一样,结果最后发现Bool不支持……所以以下代码请按C++编译
我还有一个问题,如果一侧只有仆人,合法么?我是按合法来处理
[ 本帖最后由 墨清扬 于 2014-10-1 00:05 编辑 ]
我还有一个问题,如果一侧只有仆人,合法么?我是按合法来处理
程序代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> const int MAXN = 600; const int MAXM = MAXN * MAXN * 2; bool valid[2][MAXN][MAXN]; // A stat can represents a situation. struct stat { // Number of businessman in the start bank. int bMan; // Number of servant in the start bank. int servant; // Whether current stat is in the start bank. bool start; }; // A single step indicates how they moves. struct step { int bMan; int servant; }; stat stats[MAXM]; step steps[2][MAXN][MAXN]; // Whether a stats is valid. bool isValid(const stat& s, int n) { int bMan = s.bMan, servant = s.servant; if(bMan < 0 || bMan > n || servant < 0 || servant > n) { return false; } if(bMan > 0 && servant > bMan) { return false; } if(bMan < n && n - servant > n - bMan) { return false; } return true; } // Tests for n businessmen and n servants whether there are ways to move safely. bool test(int n) { int head = 0, tail = 0, i, j, bMan = n, servant = n, start = true; step currStep; stat tmp; // Initializes. memset(valid, 0, sizeof(valid)); valid[start][bMan][servant] = true; stat curr; curr.bMan = bMan; curr.servant = servant; curr.start = start; stats[tail++] = curr; // BFS all possible status. while(head < tail) { curr = stats[head++]; if(curr.bMan == 0 && curr.servant == 0 && !curr.start) { break; } for(i = 0; i <= 2; ++i) { for(j = i ? 0 : 1; i + j <= 2; ++j) { tmp = curr; tmp.start = !tmp.start; if(curr.start) { tmp.bMan -= i; tmp.servant -= j; } else { tmp.bMan += i; tmp.servant += j; } if(isValid(tmp, n)) { bMan = tmp.bMan; servant = tmp.servant; start = tmp.start; if(!valid[start][bMan][servant]) { currStep.bMan = i; currStep.servant = j; steps[start][bMan][servant] = currStep; stats[tail++] = tmp; } valid[start][bMan][servant] = true; } } } } return valid[0][0][0]; } int main() { int n; int bMan = 0, servant = 0, start = false; step currStep; scanf("%d", &n); if(!test(n)) { printf("No\n"); return 0; } printf("\tbMan\tservant\n"); while(bMan != n || servant != n || !start) { currStep = steps[start][bMan][servant]; printf("%s\t%d\t%d\n", start ? "Back" : "Go", currStep.bMan, currStep.servant); if(!start) { bMan += currStep.bMan; servant += currStep.servant; } else { bMan -= currStep.bMan; servant -= currStep.servant; } start = !start; } return 0; }
[ 本帖最后由 墨清扬 于 2014-10-1 00:05 编辑 ]
酱油实习生