二、stl ,模拟,贪心等 [Cloned] Y - 栈

原题:

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. 

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. 

题意:

依然是栈的问题,给出两个字符串,问以第一个字符串能否通过进出栈转化为第二个字符串,如果可以则表示出进出栈顺序。

题解:

因为这个题给出的字符串中有相同的字符了,所以不能像上一个题直接用栈顶元素来比较,所以用深搜来搜索能否输出,深搜的同时定义输出数组来记录进出栈顺序。深搜思路也比较简单,先是进栈然后深搜然后出栈,截止条件是sourpos==序列长度,然后如果栈顶元素和要求序列相同,就出栈然后深搜再记录。(感觉好难说.....)

代码:AC

#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
char sourStr[1000];
char destStr[1000];
int outputStr[2000];
stack<char> *st;
int sourPos,destPos;
int inputLen;

void output()
{
    int i;
    for(i=0;i<inputLen*2;i++)
        printf("%c ",outputStr[i]==0?'o':'i');
    printf("\n");
}

void dfs(int k)
{
    if(destPos==inputLen)
        output();
    else
    {
        if(sourPos<inputLen)
        {
            outputStr[k]=1;
            st->push(sourStr[sourPos]);
            sourPos++;
            dfs(k+1);
            sourPos--;
            st->pop();
            outputStr[k]=-1;
        }
        if(!st->empty() && st->top()==destStr[destPos])
        {
            outputStr[k]=0;
            st->pop();
            destPos++;
            dfs(k+1);
            destPos--;
            st->push(destStr[destPos]);
            outputStr[k]=-1;
        }
    }
}

int main()
{
    st=new stack<char>;
    while(scanf("%s\n%s",&sourStr,&destStr)!=EOF)
    {
        printf("[\n");
        sourPos=destPos=0;
        inputLen=strlen(sourStr);
        dfs(0);
        printf("]\n");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值