void move(int n, char from, char to) { cout << "from " << from << " move " << n << " to " << to << endl; cnt++; }
hanoinode GetTop(Sqstack S) { hanoinode e; e = *--S.top; return e; } bool Pop(Sqstack &S) { if (S.top == S.base) return 0; hanoinode e; e = *--S.top; return 1; } void hanoi(int n, char from, char pass, char to) { Sqstack s; Initstack(s); hanoinode par_outer = { n,from,pass,to }; while (!(par_outer.n == 0 && s.top == s.base)) { hanoinode par_inner = par_outer; while (par_inner.n > 0) { push(s, par_inner); par_inner.n--; swap(par_inner.pass, par_inner.to); }
par_outer = GetTop(s); Pop(s); move(par_outer.n, par_outer.from, par_outer.to); par_outer.n--; swap(par_outer.from, par_outer.pass); } } int main() { int n; cin >> n; hanoi(n, 'a', 'b', 'c'); cout << endl <<"共进行了" << cnt << "次"; return 0; }
|