A little understanding of Hanoi

Source: Internet
Author: User

Taking Nefu 200 as an example

Test instructions

Chinese Nefu 200

Ideas:

Using the idea of recursion to solve very understood

There are also better-understood ideas like recursion: av7398130 and av7539453.

Recursive code:

Procedure Code:

#include <iostream>


using namespace std;
Long long steps,i=0;
int move (int x)
{
    i=!i;
    steps+=2;
    if (i)
    {
        cout<< "Move 1 from A to B" <<endl;
        cout<< "Move 1 from B to C" <<endl;
    }
    else
    {
        cout<< "Move 1 from C to B" <<endl;
        cout<< "Move 1 from B to A" <<endl;
    }
int mission (int x,char A,char B,char c)
{
    if (x==1)
    move (1);
    else
    {
        Mission (X-1,A,B,C);
        steps++;
        cout<< "Move" <<x<< "from" <<a<< "to" <<b<<endl;
        Mission (X-1,C,B,A);
        steps++;
        cout<< "Move" <<x<< "from" <<b<< "to" <<c<<endl;
        Mission (X-1,A,B,C);
    }
}
int main ()
{
    int n;
    while (Cin>>n)
    {
        steps=0;
        Mission (N, ' A ', ' B ', ' C ');
        cout<< "Total Steps is" <<steps<<endl;
    }
}

Pedometer Code:

#include <iostream>

using namespace std;

int main ()
{
    int n;
    a long long sum;
    while (Cin>>n)
    {
        sum=2;
        for (int i=1;i<n;i++)
        sum=sum*3+2;
        cout<<sum<<endl;
    }
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.