Original question: zoj 3675 http://acm.zju.edu.cn/onlinejudge/showProblem.do? Problemcode = 3675.
According to M <= 20, a binary number can be used to indicate the nail state. A maximum of 2 ^ 20 is available. The initial state is 0, indicating that the nails are not cut, and then BFS finds the solution, each time you enumerate the two directions of the scissors, You can enumerate the number of moving digits to expand the state.
Code:
# Include <iostream> # include <cstdio> # include <cstring> # include <cmath> # include <algorithm> # include <queue> using namespace STD; # define n 10007 struct node {int state, step; node (INT _ state, int _ step) {state = _ state; step = _ step;} node () {}}; int vis [1 <21]; int cut [2]; // two-direction queue <node> que; int n, m; int BFS (int s) {int I, j, k; memset (VIS, 0, sizeof (VIS); While (! Que. empty () que. pop (); int e = (1 <m)-1; que. push (node (S, 0); vis [s] = 1; while (! Que. empty () {node TMP = que. front (); que. pop (); int state = TMP. state; int step = TMP. step; int TMS = State; for (I = 0; I <2; I ++) // direction {for (j = 0; j <n; j ++) // move {int end = (cut [I]> J) | TMS) & E; // & E: Keep M bit if (vis [end]) continue; vis [end] = 1; if (END = e) return step + 1; que. push (node (end, step + 1) ;}for (j = 0; j <m; j ++) {int to = (cut [I] <j) | TMS) & E; If (vis [to]) continue; vis [to] = 1; if (to = e) return step + 1; que. push (node (to, step + 1) ;}} return-1 ;}int main () {int I, j; char ss [13]; while (scanf ("% d", & N )! = EOF) {cut [0] = cut [1] = 0; scanf ("% s", SS); for (I = 0; I <= N; I ++) {If (ss [I] = '*') {cut [0] | = (1 <I ); cut [1] | = (1 <(n-1-i) ;}} scanf ("% d", & M); If (cut [0] = 0) {puts ("-1"); continue;} printf ("% d \ n", BFs (0);} return 0 ;}
View code