回溯算法之Anagrams by Stack

该博客讨论如何使用回溯算法通过栈操作将源字符串转换为目标字符串。输入为单词对,输出为所有可能的合法i(推入)和o(弹出)序列。当源和目标字符串具有相同字符计数时,存在有效序列。示例包括将'FOO'转换为'OOF'的序列。博客提供了解题步骤,主要函数接口和C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Anagrams by Stack

 

How can anagrams result from sequences ofstack operations? There are two sequences of stack operators which can convertTROT to TORT:

[

i i i i o o o o

i o i i o o i o

]

where i stands for Pushand o stands for Pop. Your program should, given pairs ofwords produce sequences of stack operations which convert the first word to thesecond.

Input

The input will consist of several lines ofinput. The first line of each pair of input lines is to be considered as asource word (which does not include the end-of-line character). The second line(again, not including the end-of-line character) of each pair is a target word.The end of input is marked by end of file.

Output

For each input pair, your program shouldproduce a sorted list of valid sequences of i and o whichproduce the target word from the source word. Each list should be delimited by

[

]

and the sequences shouldbe printed in "dictionary order". Within each sequence, each i and o isfollowed by a single space and each sequence is terminated by a new line.

Process

A stack is a data storage and retrievalstructure permitting two operations:

Push - to insert an item and
Pop - to retrieve the most recently pushed item

We will use the symbol i (in)for push and o (out) for pop operations for an initially emptystack of characters. Given an input word, some sequences of push and popoperations are valid in that every character of the word is both pushed andpopped, and furthermore, no attempt is ever made to pop the empty stack. Forexample, if the word FOO is input, then the sequence:

i i o i o o

is valid, but

i i o

is not (it's too short), neither is

i i o o o i

(there's an illegal pop of an empty stack)

Valid sequences yield rearrangements ofthe letters in an input word. For example, the input word FOO and the sequence i i o i o o produce the anagram OOF. So alsowould the sequence i i io o o. You are to writea program to input pairs of words and output all the valid sequences of i and o which willproduce the second member of each pair from the first.

Sample Input

madam

adamm

bahama

bahama

long

short

eric

rice

Sample Output

[

i i i i o o o i o o

i i i i o o o o i o

i i o i o i o i o o

i i o i o i o o i o

]

[

i o i i i o o i i o o o

i o i i i o o o i o i o

i o i o i o i i i o o o

i o i o i o i o i o i o

]

[

]

[

i i o i o i o o

]

 

 

题目意思,就是利用栈使得源字符串经过优先步骤后变成目标字符串。

解题步骤:

本题是典型的回溯算法,可以参考深度优先算法。

在本程序中,source存储的是源字符串,target存储的是目标字符串,

medianchar相当于栈的作用,用来存储栈数据的变化,charstack记录的是进出栈的步骤。这几个均为全局变量。下面给出主要函数接口:

inandout(intsleft,int tleft,int mleft,int cleft),sleft表示即将要入栈的源字符串的位置,tleft表示即将要和栈顶元素比较的目标字符串的位置,mleft表示栈顶元素的下一个位置,cleft表示记录进出栈步骤

具体的程序如下:

 

#include<iostream>

usingnamespace std;

 

#definemaxchar 200

 

char source[maxchar];      //源字符串

chartarget[maxchar];       //目标字符串

charmedianchar[maxchar];   //栈

charcharstack[2*maxchar];   //顺序记录进出栈

intsourcekey[26];              //用来统计源字符串字符出现的次数

inttargetkey[26];         //用来统计目标字符串出现的次数

int length;                       //源字符串长度

 

voidInit();        //初始化

boolisMatch();             //判断是否匹配

voidresult();           //输出结果

voidinandout(int sleft,int tleft,int mleft,int cleft);//主要函数

int main()

{

       Init();

       while((cin>>source)&&(cin>>target))

       {

              bool ismatch=isMatch();

              if(ismatch)

              {

                     cout<<"["<<endl;

                     result();

                     cout<<"]"<<endl;

              }

              else

              {

                     cout<<"["<<endl;

                     cout<<"]"<<endl;

              }

              Init();

       }

       return 0;

}

void Init()

{

       for(int i=0;i<maxchar;i++)

       {

              source[i]='\0';

              target[i]='\0';

              medianchar[i]='\0';

       }

       for(int i=0;i<2*maxchar;i++)

       {

              charstack[i]='\0';

       }

       for(int i=0;i<26;i++)

       {

              sourcekey[i]=0;

              targetkey[i]=0;

       }

       length=0;

}

boolisMatch()

{

       //原理:通过比较源字符串和目标字符串中字符出现次数来判断是否能通过栈达到

       for(int i=0;source[i]!='\0';i++)

       {

              sourcekey[source[i]-'a']+=1;

              length=i+1;

       }

       for(int i=0;target[i]!='\0';i++)

       {

              targetkey[target[i]-'a']+=1;

       }

       for(int i=0;i<26;i++)

       {

              if(sourcekey[i]!=targetkey[i])

                     return false;

       }

       return true;

}

voidresult()

{

       inandout(0,0,0,0);

}

voidinandout(int sleft,int tleft,int mleft,int cleft)

{

       if((sleft<=length)&&(tleft<=length)&&(mleft<=length)&&(cleft<=2*length))

       {

              if(mleft==0)

              {

                     if(cleft==2*length)

                     {

                            for(inti=0;i<2*length-1;i++)

                                   cout<<charstack[i]<<"";

                            cout<<charstack[2*length-1]<<""<<endl;

                     }

                     if(sleft<length)

                     {

                            charstack[cleft]='i';

                            medianchar[mleft]=source[sleft];

                            inandout(sleft+1,tleft,mleft+1,cleft+1);

                     }

              }

              else

              {

                    

                     if(medianchar[mleft-1]==target[tleft])

                     {

                            if(sleft<length)

                            {

                                   charstack[cleft]='i';

                                   medianchar[mleft]=source[sleft];

                                   inandout(sleft+1,tleft,mleft+1,cleft+1);

                            }

                            charstack[cleft]='o';

                            inandout(sleft,tleft+1,mleft-1,cleft+1);

                     }

                     else

                     {

                            if((cleft<2*length)&&(mleft<length)&&(sleft<length))

                            {

                                   charstack[cleft]='i';

                                   medianchar[mleft]=source[sleft];

                                   inandout(sleft+1,tleft,mleft+1,cleft+1);

                            }

                     }

              }

       }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值