My question basically a modified of a question of this link Modified Tower of Hanoi
In that question, it assumes that some of the discs have same size. My question is a little more complicated. Let's assume those discs with same size having different color. And when you move those discs from a to c, you have to make sure that the discs should be in the same order as it was placed at the beginning. We need to find the least moves of this problem.
I have an example here.
As you can see, if we have 1 disc whose size is 1 and 2 discs whose size are 2. We at least need to move 7 times.
Thx for Kenny Ostrom. Now firstly, I know if you have multiple same sized plates on the bottom, then you must take the one bottom plate and pretend it is larger than the others, even if it is the same size. And secondly, I think for a group of discs of same size which is in the middle, every disc except the bottom one should be moved twice because we try to have a right order.
However, it does not seem to lead to the right answer.
It is a question of our c++ homework and the questions gives:
N represents how many size of disc do we have, which is between 1 and 15000
M is just a number, which is between 1 and 1000000.
a[i] represents the number of the disc whose size is i
and I need to print out (the least number of the moves) mod M. So i am guessing maybe there should be a better way to calculate (2^n) mod M?
Here is my code:
#include<iostream>
#include <math.h>
using namespace std;
int main()
{
int N,M; //for an example:N=2,M=1000
cin>>N>>M;
int *a=new int[N+2];
for(int i=1;i<=N;i++) cin>>a[i]; //I abandon the first element of this array
// just to make it easier for after
// for an example: {0,1,2}
if(a[N]>1){ //take the bottom one as a seperate group
a[N]=a[N]-1;
a[N+1]=1;
}
int j=N+1;
int num=0;
for(int i=1;i<=j;i++){
if(a[i]<=1){
num=num+pow(2,j-i);
}
else{
num=num+pow(2,j-i)*(2*(a[i]-1)+1);//for every group of discs in the middle
}
}
cout<<num;
cout<<num%M;
return 0;
}
Any suggestions or pointers are welcome. Thanks!