ZJU 1004 有注释,大侠请进!

Viali 2003-09-13 05:26:32
偶的回溯很烂,程序写出来了,得不到结果,请大侠们帮忙改正,谢谢了....

#include<iostream>
#include<string>
using namespace std;
#define max 100 //最长字符长度 max
char source[max], target[max], stack[max],tem[max],operate[2*max];
//tem数组是记录在operate操作下最终得到的结果,若tem==target则,operate序列输出
int len;
void output()
{
for(int i=0;i<2*len;i++)
cout<<operate[i]<<" ";
cout<<endl;
}
void search(int p,int s,int i,int t)
//source[p]将要处理,stack[s]、tem[i]、operate[t]已存在
{
if(s>= len || i>= len || t>=2*len) return ;
if( p>= len)
{
while(s!=-1)// 将堆栈中的东西全部出栈
{
tem[i++]=stack[s];
operate[t++]='o';
s--;
}
tem[len]=target[len];
if(strcmp(tem,target)==0)
output();
}

operate[t+1]='i';//可以选择source[p]先进栈
stack[s+1]=source[p];
search(p+1,s+1,i,t+1);

if(s!=-1)//即 若栈不为空,栈顶元素可以选择先出栈,然后再处理source[p]
{
operate[t+1]='o';
tem[i+1]=stack[s];
search(p,s-1,i+1,t+1);
}
}
int main()
{
while(cin>>source>>target)
{
len=strlen(source);
cout<<"["<<endl;
//--------------------------------------
search(0,-1,-1,-1);//调用
//--------------------------------------
cout<<"]"<<endl;
}
return 1;
}
...全文
40 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
loewe 2003-09-13
  • 打赏
  • 举报
回复
#include <stdio.h>
char source[100],target[100],stack[100],outstack[100];
int temp[200];
int v,len;

int init(int a)
{
int i,j,k;
if (scanf("%s",&source)!=EOF)
{ scanf("%s",&target);
i=strlen(source);
j=strlen(target);
if (i!=j) v=1;
else { len=i; return(1);}
a++;
}
else return(0);
}

void search(int top1,int top2,int top3,int tpoint)
{
int i,j,k;
if ((tpoint==2*len)&&(strcmp(target,outstack)==0))
{
for (i=0;i<2*len;i++)
if (temp[i]==1) printf("i ");
else printf("o ");
printf("\n");
}
if ((top2<len)&&(top1<len))
{
stack[top2]=source[top1];
stack[top2+1]='\0';
temp[tpoint]=1;
search(top1+1,top2+1,top3,tpoint+1);
temp[tpoint]=0;
stack[top2]='\0';
}
if ((top2>=1)&&(top3<len))
{
outstack[top3]=stack[top2-1];
outstack[top3+1]='\0';
stack[top2-1]='\0';
temp[tpoint]=-1;
search(top1,top2-1,top3+1,tpoint+1);
temp[tpoint]=0;
stack[top2-1]=outstack[top3];
outstack[top3]='\0';
}
}
main()
{
v=0;
while (init(1)!=0)
{
printf("[\n");
if (v==0)
{
search(0,0,0,0);
}
printf("]\n");
v=0;
}
}
ZhangYv 2003-09-13
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/2068/2068297.xml?temp=.4777948
ZhangYv 2003-09-13
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/2068/2068297.xml?temp=.4777948

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧