#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#define getHead(X) pegs[(X)][top[(X)]]
#define popHead(X) top[(X)] -= 1;
#define pushHead(X,Y) top[(X)] += 1; pegs[(X)][top[(X)]] = Y;
int main(){
int disks;
FILE * fin = fopen("hanoi.in","r");
fscanf(fin,"%d", &(disks));
fclose(fin);
FILE * fout = fopen("hanoi.out","w");
int i;
int pegs[3][disks+1];
for (i = 0; i <= disks; i++){
pegs[0][i] = 0;
pegs[1][i] = 0;
pegs[2][i] = 0;
}
int top[3] ={-1,-1,-1};
for (i = 0; i < 3; i++){
pushHead(i,INT_MAX);
}
for (i = disks; i > 0; i--){
pushHead(0,i);
}
int step = (disks % 2) + 1;
int topPeg = 0, newPos;
int PPA, PPB;
while(1){
newPos = (topPeg+step)%3;
fprintf(fout,"%c %c\n", (char)(topPeg+'A'), (char)(newPos+'A'));
popHead(topPeg);
pushHead(newPos,1);
if (top[2] == disks)
break;
PPA = (newPos + 1) % 3;
PPB = (newPos + 2) % 3;
if (getHead(PPA) < getHead(PPB)){
pushHead(PPB, getHead(PPA));
popHead(PPA);
fprintf(fout,"%c %c\n", (char)(PPA+'A'), (char)(PPB+'A'));
}else{
pushHead(PPA, getHead(PPB));
popHead(PPB);
fprintf(fout,"%c %c\n", (char)(PPB+'A'), (char)(PPA+'A'));
}
topPeg = newPos;
}
fclose(fout);
return 0;
}
|
#include <iostream>
#include <fstream>
#include <limits.h>
using namespace std;
#define getHead(X) pegs[(X)][top[(X)]]
#define popHead(X) top[(X)] -= 1;
#define pushHead(X,Y) top[(X)] += 1; pegs[(X)][top[(X)]] = Y;
void explore(int disks, ofstream& fout){
int i;
int pegs[3][disks+1];
for (i = 0; i <= disks; i++){
pegs[0][i] = 0;
pegs[1][i] = 0;
pegs[2][i] = 0;
}
int top[3] ={-1,-1,-1};
for (i = 0; i < 3; i++){
pushHead(i,INT_MAX);
}
for (i = disks; i > 0; i--){
pushHead(0,i);
}
int step = (disks % 2) + 1;
int topPeg = 0, newPos;
int PPA, PPB;
while(1){
newPos = (topPeg+step)%3;
fout << (char)(topPeg+'A') << " " << (char)(newPos+'A') << endl;
popHead(topPeg);
pushHead(newPos,1);
if (top[2] == disks)
break;
PPA = (newPos + 1) % 3;
PPB = (newPos + 2) % 3;
if (getHead(PPA) < getHead(PPB)){
pushHead(PPB, getHead(PPA));
popHead(PPA);
fout << (char)(PPA+'A') << " " << (char)(PPB+'A') << endl;
}else{
pushHead(PPA, getHead(PPB));
popHead(PPB);
fout << (char)(PPB+'A') << " " << (char)(PPA+'A') << endl;
}
topPeg = newPos;
}
}
int main(){
int disks;
ifstream fin("hanoi.in");
fin >> disks;
fin.close();
ofstream fout ("hanoi.out");
explore(disks, fout);
fout.close();
return 0;
}
|