典型的河内问题解决方案塔将如下:
void hanoi(int diskNumber , int start, int temp, int finish)
{
if(diskNumber == 1)
{
cout<< " Move Disk " << diskNumber<<" from " << start <<" to "<< finish<<endl;
}
else
{
hanoi(diskNumber-1,start,temp,finish);
cout<<"Move Disk from " << start <<" to "<<finish<<endl;
hanoi(diskNumber - 1,temp,start,finish);
}
}
但我想要做的是计算算法运行的时间。因此:
int main
{
//Hanoi:
cout<<"Hanoi Tower Problem:"<<endl;
//3 Disks:
clock_t htimer3 = clock();
hanoi(3, 1,2,3);
cout<<"CPU Time for n = 3 is: "
<<clock() - htimer3/CLOCKS_PER_SEC<<endl;
//6 Disks:
clock_t htimer6 = clock();
hanoi(6, 1,2,3);
cout<<"CPU Time for n = 6 is: "
<<clock() - htimer6/CLOCKS_PER_SEC<<endl;
//9 Disks:
clock_t htimer9 = clock();
hanoi(9, 1,2,3);
cout<<"CPU Time for n = 9 is: "
<<clock() - htimer9/CLOCKS_PER_SEC<<endl;
//12 Disks:
clock_t htimer12 = clock();
hanoi(12, 1,2,3);
cout<<"CPU Time for n = 12 is: "
<<clock() - htimer12/CLOCKS_PER_SEC<<endl;
//15 Disks:
clock_t htimer15 = clock();
hanoi(15, 1,2,3);
cout<<"CPU Time for n = 15 is: "
<<clock() - htimer15/CLOCKS_PER_SEC<<endl;
//End of Hanoi Tower Problem
return 0;
}
这里的问题是,例如,如果我设置diskNumber = 15,代码将运行32767次,这将填充终端窗口,并且我将丢失之前生成的行(我必须计算一些其他算法,如冒泡排序快速排序等。我将使用数字绘制图表以后代表他们的大O,即:河内塔的大O算法是2 ^ n)。 为了解决这个问题,我修改了代码:
void hanoi(int diskSize, int start, int finish, int temp)
{
if(diskSize == 1)
{
return;
}
else
{
hanoi(diskSize - 1, start, temp, finish);
hanoi(diskSize - 1, temp, finish, start);
}
}
我的主要问题:修改后的代码是否采用与原始算法相同的运行时间?如果没有,该怎么办?有什么建议?
答案 0 :(得分:0)
是的,修改后的代码的时间复杂度与前一个相同,因为cout
需要恒定的时间。因此,考虑到您要写入的流,您的运行时间不会受到太大影响(粒度将在纳秒级)。
我建议将输出重定向到文件。 例如:
./executable > FileName