CSES – Tower of Hanoi

遞迴

#include<bits/stdc++.h>
#define int long long
#define double long double
#define f first
#define s second
#define fastio ios_base::sync_with_stdio(false);cin.tie(0)
using namespace std;
int n,cnt=0;
vector<pair<int,int>> ans;
void hanoi(int from, int to, int another, int N){
    if(N == 1){
        ans.push_back({from,to});
        cnt++;
        return;
    }
    hanoi(from,another,to,N-1);
    hanoi(from,to,another,1);
    hanoi(another,to,from,N-1);
}
signed main(){
    fastio;
    cin>>n;
    hanoi(1,3,2,n);
    cout<<cnt<<"\n";
    for(pair<int,int>p : ans) cout<<p.f<<" "<<p.s<<"\n";
    return 0;
}

相關文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *