sudama_bera

tower_of_hanoi_cf

Jun 7th, 2026
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | Source Code | 0 0
  1. int n;
  2. vector<int>a;
  3. vector<vector<int>>ans;
  4. void moveall(int k,int src,int dest){
  5.     if(k<=0)return;
  6.     int aux=6-src-dest;
  7.     if(a[k-1]==0){
  8.        // move up k-1 to aux, then move kth to dest, then move k-1 from aux to dest
  9.         moveall(k-1,src,aux);
  10.         ans.push_back({k,src,dest});
  11.         moveall(k-1,aux,dest);
  12.     }else{
  13.         // keep a[k-1]+1 lowest rings to source, move k-a[k-1]-1 to aux
  14.         // then move kth to dest
  15.         // then move the k-a[k-1]-1 from aux to source back
  16.         //then call the recursion again for (k-1)th
  17.         moveall(k-a[k-1]-1,src,aux);
  18.         ans.push_back({k,src,dest});
  19.         moveall(k-a[k-1]-1,aux,src);
  20.         moveall(k-1,src,dest);
  21.     }
  22. }
  23. void solve() {
  24.     cin>>n;
  25.     a.resize(n);
  26.     bool ok=true;
  27.     for(int i=0;i<n;i++){
  28.         cin>>a[i];
  29.     }
  30.     for(int i=0;i<n;i++){
  31.         if(a[i]>i){
  32.             ok=false;break;
  33.         }
  34.     }
  35.   if(!ok){
  36.     cout<<"No"<<endl;return;
  37.   }
  38.   cout<<"Yes"<<endl;
  39.   //s,a,d
  40.   //f(n,s,d)
  41.   moveall(n,1,3);
  42.   cout<<ans.size()<<endl;
  43.   for(auto&vec:ans){
  44.     cout<<vec[0]<<" "<<vec[1]<<" "<<vec[2]<<endl;
  45.   }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment