1.桃子到底有多少
-
问题描述:某人某日摘若干桃子,每天卖出一半并且吃掉一个,最后一天(第n天)剩下一个。
-
编写一个递归程序,天数n作为参数,计算一共摘了多少桃子。
-
分析问题可以得出以下的递推函数:
-
f(1) = 1 n=1
-
f(n) = 2 * ( f(n-1) + 1 ) n>1
-
桃子问题算法程序:分别用递归和递推实现
其实挺简单的:
#include<stdio.h>
long peach1(int n);
long peach2(int n);
int main(void)
{
int i;
for(i=1;i<10;i++)
printf("%d %ld %ld\n",i,peach1(i),peach2(i));
return 0;
}
long peach1(int n){
if(n==1)
return 1;
else
return 2*(peach1(n-1)+1);
}
long peach2(int n){
if(n==1)
return 1;
else{
long res=1L;
while(n>1){
res=2*(res+1);
n--;
}
return res;
}
}
结果:
2.中国马的跳法
问题:中国象棋的半张棋盘上,马从左下角跳到右上角,总共有几种跳法。
求所有跳法,需要用穷尽搜索,试探法即回溯法是首选。
程序中,以左上角坐标为(0,0),马从左下角(4,0)跳到右上角(0,8)。
马在某个位置,一般而言有8种跳法,但是由于规定只能往右跳,所以只有4种跳法。同时如果跳出棋盘外则回溯。
为了在马跳到目的地后输出结果,使用堆栈存储马跳的轨迹。
总共有37种跳法。
#include<stdio.h>
int stackrow[100];
int stackcol[100];
int ps=100;
int count=0;
void horse(int row,int col);
void push(int row,int col);
void pop();
void output_result();
int main(void)
{
horse(4,0);
return 0;
}
/*函数功能:当前马调到row行col列;
*参数:row--行,col--列
*/
void horse(int row,int col){
push(row,col);
if(row==0&&col==8)
output_result();
if(row<0||row>4||col>8){
;
}
else{
horse(row-2,col+1);
horse(row-1,col+2);
horse(row+1,col+2);
horse(row+2,col+1);
}
pop();
}
void push(int row,int col){
stackrow[ps]=row;
stackcol[ps]=col;
ps++;
}
void pop(){
ps--;
}
void output_result(){
count++;
int i;
printf("result %d\n",count);
for(i=0;i<ps;i++){
printf("%2d: %d %d\n",i+1,stackrow[i],stackcol[i]);
}
printf("\n");
getchar();
}
3.国际马的跳法
问题:国际象棋的棋盘上,马从左上角跳到跳到右下角,总共有几种跳法。
这个问题与中国象棋的棋盘上的跳马问题完全相同,只是起始和终止坐标的不同。但是,可以比较一下所有跳法的数量,了解问题复杂度的差异。
求所有跳法,需要用穷尽搜索,试探法即回溯法是首选。
程序中,以左上角坐标为(0,0),马从左上角(0,0)跳到右下角(7,7)。
马在某个位置,一般而言有8种跳法,但是由于规定只能往右跳,所以只有4种跳法。同时如果跳出棋盘外则回溯。
为了在马跳到目的地后输出结果,使用堆栈存储马跳的轨迹。
总共有18种跳法。与中国象棋半张棋盘上37种跳法相比,可以说中国象棋问题的复杂度更高。
#include<stdio.h>
#define STACK_SIZE 100
struct stack{
int row;
int col;
}stack[STACK_SIZE];
int ps=0;
int count=0;
void horse(int row,int col);
void push(int row,int col);
void pop();
void output_result();
int main(void)
{
horse(0,0);
return 0;
}
/*函数功能:当前马调到row行col列;
*参数:row--行,col--列
*/
void horse(int row,int col){
push(row,col);
if(row==7&&col==7)
output_result();
if(row<0||row>7||col>7){
;
}
else{
horse(row-2,col+1);
horse(row-1,col+2);
horse(row+1,col+2);
horse(row+2,col+1);
}
pop();
}
void push(int row,int col){
stack[ps].row=row;
stack[ps].col=col;
ps++;
}
void pop(){
ps--;
}
void output_result(){
count++;
int i;
printf("result %d\n",count);
for(i=0;i<ps;i++){
printf("%2d: %d %d\n",i+1,stack[i].row,stack[i].col);
}
printf("\n");
getchar();
}