记录详情

Accepted


  
# 状态 耗时 内存占用
#1 Accepted 1ms 344.0 KiB
#2 Accepted 1ms 380.0 KiB
#3 Accepted 1ms 372.0 KiB
#4 Accepted 1ms 376.0 KiB
#5 Accepted 27ms 376.0 KiB

代码

#include <iostream>
#include<cmath> 
using namespace std;
void hnt(int n,int k,char A, char B, char C);
int step=1; 
int a=0,b=0,c=0;
int main()
{
  int n,k;
  
  cin>>n>>k;
 // n=6;k=10;
  

	 
	
  for (int i=1;i<=n;i++)
     a=a+pow(2,i-1);
  //cout<<a<<endl;

  hnt(n,k,'A','B','C');
  
  return 0;
 }

void hnt(int n,int k,char A, char B, char C)
{  
   if (n<=0)
      return;
    else
      if (n == 1)
	    {
		//圆盘只有一个时,只需将其从A塔移到C塔
		//cout << "第"<<step++<<"步/"<<"move " << n << " from " << A << " to " << C << endl;
		  step++;
		  if(A=='A')
		    a=a-pow(2,n-1);
		  if(A=='B')
		    b=b-pow(2,n-1);
		  if(A=='C')
		    c=c-pow(2,n-1);
		  if(C=='A') 
		    a=a+pow(2,n-1);
		  if(C=='B') 
		    b=b+pow(2,n-1);
		  if(C=='C') 
		    c=c+pow(2,n-1);
	    // cout<<a<<" "<<b<<" "<<c<<endl;
	      if (step-1==k)	        
	       {//cout<<k<<endl;
	        cout<<a<<" "<<b<<" "<<c<<endl;
	       }
		//cout << "第"<<step++<<"步/"<<"move " << pow(2,n-1) << " from " << a<< " to " << c << endl<<endl;
	
	   
	    
     	}
	  else
	    {
		hnt(n - 1, k,A,C,B);//递归,把A塔上编号1~n-1的圆盘移到B上,以C为辅助塔
		
		//cout  << "第"<<step++<<"步/"<< "move " << n << " from " << A << " to " << C << endl;//把A塔上编号为n的圆盘移到C上
		step++;
		if(A=='A')
		    a=a-pow(2,n-1);
		  if(A=='B')
		    b=b-pow(2,n-1);
		  if(A=='C')
		    c=c-pow(2,n-1);
		  if(C=='A') 
		    a=a+pow(2,n-1);
		  if(C=='B') 
		    b=b+pow(2,n-1);
		  if(C=='C') 
		    c=c+pow(2,n-1);
		// cout<<a<<" "<<b<<" "<<c<<endl;
		  
		 
		//cout << "第"<<step++<<"步/"<<"move " << pow(2,n-1) << " from " << a << " to " << c << endl<<endl;
	
	
	
	   
		  
	  	if (step-1==k)	        
	       {//cout<<k<<endl;
	        cout<<a<<" "<<b<<" "<<c<<endl;
			
	       //cout<<suma<<"/"<<sumb<<"/"<<sumc<<endl; 
		    }
		   
		hnt(n - 1,k, B,A,C);//递归,把B塔上编号1~n-1的圆盘移到C上,以A为辅助塔
	   }

	
}
 

信息

递交者
类型
递交
题目
P1017 2-3 Hanoi游戏的状态
语言
C++
递交时间
2021-07-20 11:05:15
评测时间
2021-07-20 11:12:06
评测机
分数
100
总耗时
32ms
峰值内存
380.0 KiB