ZOJ Problem Set - 1004 Anagrams by Stack (回溯法)

ZOJ Problem Set - 1004

Anagrams by Stack


Time Limit: 2 Seconds      Memory Limit: 65536 KB


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

[
i i i i o o o o
i o i i o o i o
]

where i stands for Push and o stands for Pop. Your program should, given pairs of words produce sequences of stack operations which convert the first word to the second.

Input

The input will consist of several lines of input. The first line of each pair of input lines is to be considered as a source 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 should produce a sorted list of valid sequences of i and o which produce the target word from the source word. Each list should be delimited by

[
]

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

Process

A stack is a data storage and retrieval structure 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 empty stack of characters. Given an input word, some sequences of push and pop operations are valid in that every character of the word is both pushed and popped, and furthermore, no attempt is ever made to pop the empty stack. For example, 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 of the 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 also would the sequence i i i o o o. You are to write a program to input pairs of words and output all the valid sequences of i and o which will produce 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
]题意:i 表示进栈 , o 表示出栈.构造出所要求输出的单词的进出栈顺序主要算法:回溯法(递归思想)
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <string>

using namespace std ; 

stack <char>build ;
vector <char> operato ;
string a , b ;
int len ; 

void DFS(int ipush , int ipop){

    if(ipush == len && ipop == len){
        for(int i=0 ; i<operato.size() ; i++){
            cout << operato[i] << " " ;
        }
        cout << endl ;
        return;
    }

    if(ipush+1 <= len ){
        build.push(a[ipush]) ;
        operato.push_back(‘i‘) ;
        DFS(ipush+1 , ipop) ;
        build.pop() ;
        operato.pop_back() ;
    }

    if(ipop+1<=ipush && ipop+1 <=len && build.top() == b[ipop]){
        char turn = build.top() ;
        build.pop() ;
        operato.push_back(‘o‘) ;
        DFS(ipush , ipop+1) ;
        operato.pop_back() ;
        build.push(turn) ;
    }
    return;
}

int main(){

    while(cin >> a >> b){
        len = a.length() ; 

        cout << ‘[‘ << endl ;
        DFS(0,0) ;
        cout << ‘]‘ << endl ;
    }
    return 0 ;
}
#include <iostream>
#include <stack>
#include <map>
#include <set>
#include <queue>
#include <vector>
#include <list>
using namespace std;
string a,b;//源单词与目标单词
stack<char> build;//构造目标字符串
vector<char> operate;//记录出入栈操作
int length;
void dfs(int ipush,int ipop)//形参ipush计录入栈操作次数,形参ipop计录出栈操作次数
{
    if(ipush==length&&ipop==length)//如果入栈操作次数和出栈·操作·次数·刚好·等于·字符串·长度·时,则·目标字符串构造完成,输出操作序列
    {
        for(int i=0;i<operate.size();i++)
            cout<<operate[i]<<" ";
            cout<<endl;
    }
    //入栈操作
    if(ipush+1<=length)
    {
        build.push(a[ipush]);//将当前字符入栈
        operate.push_back(‘i‘);//计录入栈操作
        dfs(ipush+1,ipop);//搜素下一个位置
        build.pop();//恢复好刚刚入栈的字符,便于下一个搜索
        operate.pop_back();//恢复入栈操作
    }
    //出栈操作
    if(ipop+1<=ipush&&ipop+1<=length&&build.top()==b[ipop])
    {
        char tc=build.top();
        build.pop();//将当前字符出栈
        operate.push_back(‘o‘);//计录出栈操作
        dfs(ipush,ipop+1);//搜索下一个位置
        build.push(tc);//恢复好刚刚出栈的字符,便于下一个搜索
        operate.pop_back();//恢复出栈操作
    }
}
int main()
{
    while(cin>>a>>b)
    {
        length=a.length();
        cout<<"["<<endl;
        dfs(0,0);
        cout<<"]"<<endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/yi-ye-zhi-qiu/p/9141580.html

时间: 2024-10-27 17:47:52

ZOJ Problem Set - 1004 Anagrams by Stack (回溯法)的相关文章

stack+DFS ZOJ 1004 Anagrams by Stack

题目传送门 1 /* 2 stack 容器的应用: 要求字典序升序输出,所以先搜索入栈的 3 然后逐个判断是否满足答案,若不满足,回溯继续搜索,输出所有符合的结果 4 */ 5 #include <cstdio> 6 #include <iostream> 7 #include <algorithm> 8 #include <stack> 9 #include <cmath> 10 #include <cstring> 11 #inc

ZOJ 1004 Anagrams by Stack

Anagrams by Stack 题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1004 题意:通过堆栈实现将一个字符串转变成目标字符串的操作,要求输出全部的可能操作组合. 思路:利用深度优先的搜索思路,对于每一个状态都有入栈和出栈两种可能的操作,由于要求按字典序输出,每次先考虑入栈再考虑出栈.即"能入就入,不能入考虑是否能退,随后返回上一步". 下面贴代码: 1 //Problem Name: A

UVA - 524 Prime Ring Problem(素数环)(回溯法)

题意:输入n,把1~n组成个环,相邻两个数之和为素数. 分析:回溯法. #pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<s

[ZOJ 1004] Anagrams by Stack (简单搜索)

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1004 题目大意:给你个栈,给你源串和目标串,按字典序输出符合要求的进站出站序列. 就是搜搜搜呗... 带上答案和模拟的栈.. 代码: 1 #include <cstdio> 2 #include <cstdlib> 3 #include <string> 4 #include <iostream> 5 #include &l

[JAVA][ZOJ 1004][Anagrams by Stack]

[java] view plaincopyprint? import java.io.BufferedInputStream; import java.util.Scanner; public class Main { static String start;// record the first str static String end;// record the rearranged str public static void dfs(char[] stack, char[] seque

1004 Anagrams by Stack

考察DFS的应用,用栈描述字符串的变化过程. 1 #include <stdio.h> 2 #include <string.h> 3 int len1,len2; 4 char str1[100],str2[100],stk[100],ans[200]; 5 6 void output(int n){ 7 int i; 8 for(i=0;i<n;i++){ 9 printf("%c ",ans[i]); 10 } 11 printf("\n&

ZOJ Problem Set - 3820 Building Fire Stations 【树的直径 + 操作 】

题目:problemId=5374" target="_blank">ZOJ Problem Set - 3820 Building Fire Stations 题意:给出n个点,n-1条边的一棵树.然后要在两个点上建立两个消防站.让全部点的到消防站最大距离的点的这个距离最小. 分析:首先先求这个树的直径.然后在树的直径的中点处把树分成两棵树.然后在把两棵树分别取中点的最大值就是ans值. 这个题目数据有点水了感觉... AC代码: #include <cstdi

ZOJ Problem Set - 1025解题报告

ZOJ Problem Set - 1025 题目分类:动态规划 原题地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1025   题目大意就是有很多木头,都有各自的长度和重量.现在要加工这些木头,如果加工某根木头的长度和重量大于等于它上一根木头的长度和重量,那么加工它不需要时 间,否则要花1分钟.现给出一堆木头的长度和重量,要求加工完这堆木头可以花的最少时间.例如给出5根木头长度重量分别为(4,9), (5,2),

ZOJ Problem Set - 3321 并查集

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3321 Circle Time Limit: 1 Second      Memory Limit: 32768 KB Your task is so easy. I will give you an undirected graph, and you just need to tell me whether the graph is just a circle.