----------------解决方案--------------------------------------------------------
??
自己先弄点东西来,,
大家好一起努力啊>.
朋友是不>>
----------------解决方案--------------------------------------------------------
没明白你的意思
----------------解决方案--------------------------------------------------------
我来解释一下:
比如m = 15, n = 4;
可以通过四步将整数15 变换为整数4:4=gfgg(15)。
也即:
(1) g(15) = 7;
(2) g(7) = 3;
(3) f(3) = 9;
(4) g(9) = 4;
----------------解决方案--------------------------------------------------------
[CODE]
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int m, n;
int counter = 0;
scanf ("%d%d", &m, &n);
while (m != n)
{
if (m > n)
{
m = m / 2;
counter++;
}
else
{
m = m * 3;
counter++;
}
}
printf ("%d", counter);
return 0;
}
----------------解决方案--------------------------------------------------------
但是最好打印出步骤,比如从5到1,打印出为g->g.
我用二叉树写了一个,但貌似有问题,而且占用内存很大。
#include "stdafx.h"
#include "malloc.h"
#define MAX 1000
#define NULL 0
int f(int x)
{
int l;
l=3*x;
return (l);
}
int g(int x)
{
int l;
l=x/2;
return (l);
}
struct Node
{
int getnumber;
struct Node *lchild,*rchild;
struct Node *pre;
};
//非递归算法生成二叉树
int qcreate(int m,int n)
{
struct Node * queue[MAX],*p,*root,*q,*before;
int front=0,rear=0;
int x;
root=NULL;
x=m;
p=(struct Node *)malloc(sizeof(struct Node));
p->getnumber=x;
p->lchild=NULL;
p->rchild=NULL;
p->pre =NULL;
while(p->getnumber !=n)
{
p=NULL;
if(x!=NULL)
{
p=(struct Node *)malloc(sizeof(struct Node));
p->getnumber=x;
p->lchild=NULL;
p->rchild=NULL;
p->pre =NULL;
}
rear++;
queue[rear]=p;//入队列
if(queue[front++]!=NULL&&p!=NULL)//父结点和子结点都不为空
{
if(rear==1)//根结点
root=p;
else
{
if(rear%2==0)
{
p=before;
queue[front++]->lchild=p;//左结点
p->pre =before;
x=f(x);
}
else
{
p=before;
queue[front+1]->rchild=p;//右结点
p->pre =before;
x=g(x);
}
if(rear%2==1)
front++;//出队列
}
}
}
q=p;
p=p->pre;
while(p!=NULL)
{
if(p->lchild =q)
{
printf("f");
}
if(p->rchild =q)
{
printf("g");
}
q=p;
p=p->pre ;
}
return 0;
}
void main()
{
int start,result;
scanf("%d%d",&start,&result);
qcreate(start,result);
}
----------------解决方案--------------------------------------------------------
#include <iostream.h>
void main()
{int m,n,s;
cout<<"m=";
cin>>m;
cout<<"n=";
cin>>n;
s=m;
while(s!=n)
if(s<=n)
{ cout<<"f("<<s<<")="<<3*s<<endl;
s=s*3;
}
else
{ cout<<"g("<<s<<")="<<s/2<<endl;
s=s/2;
}
}
----------------解决方案--------------------------------------------------------
#include<stdio.h>
void main()
{
int m,n;
int counter=0;
int x;
printf("输入要变换前的数和要变换后的数:");
scanf(" %d , %d(两数间用,隔开)",&m,&n);
while(m!=n)
if(m>n)
{
x=m;
m=m/2;
printf("第%d次变换 g(%d)=%d\n",++counter,x,m);
}
else
{
x=m;
m=3*m;
printf("第%d次变换 f(%d)=%d\n",++counter,x,m);
}
printf("\n共经过%d次变换\n",counter);
}
----------------解决方案--------------------------------------------------------