算法题 Anagrams by Stack

Anagrams by Stack from ZOJ(浙大OJ) Problem Set - 1004,链接http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1004

题目如下:

 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 为出栈,现在给两个字符串st1,st2,现在要将st1转化为st2,转化方法是,st1中字符从头开始入栈,并合理出栈构造出st2。请输出所有可能的出入栈步骤。

解这道题目的主要思路就是用深度优先遍历算法,把所有情况都遍历一遍,然后把符合题目的情况打印出来。

没有比较就没有伤害,这道题目我自己先写了一遍,虽然提交成功了,但是代码过于冗余,下面我贴一下我自己的代码和大佬写的代码,以便警醒我实力的不足。

我写的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define NONE 0
#define PUSH 1
#define POP 2

typedef struct
{
    char data[0x100];
    char str[0x100];
    char behavior[0x100];
    int length;
    int b_l;
    int s_l;
} stack;

void print(stack *s)
{
    int len, i;
    len = s->s_l * 2;
    for (i = 0; i < len; i++)
    {
        if (s->behavior[i] == PUSH)
        {
            printf("i ");
        }
        else if (s->behavior[i] == POP)
        {
            printf("o ");
        }
        else
        {
            fprintf(stderr, "Error\n");
            exit(0);
        }
    }
    puts("");
}

void push(stack *s, char ch)
{
    s->behavior[s->b_l] = PUSH;
    s->b_l++;

    s->data[s->length] = ch;
    s->length++;
}

void r_push(stack *s)
{
    s->b_l--;
    s->behavior[s->b_l] = NONE;

    s->length--;
    s->data[s->length] = NONE;
}

void pop(stack *s)
{
    char ch;
    s->behavior[s->b_l] = POP;
    s->b_l++;

    ch = s->data[s->length - 1];
    s->length--;

    s->str[s->s_l] = ch;
    s->s_l++;
}

void r_pop(stack *s)
{
    char ch;
    s->b_l--;
    s->behavior[s->b_l] = NONE;

    s->s_l--;
    ch = s->str[s->s_l];

    s->length++;
    s->data[s->length - 1] = ch;
}

void dfs(stack *s, char *dest, char *src, int length, int num)
{
    int i;
    if (s->s_l == length)
    {
        for (i = 0; i < length && s->str[i] == dest[i]; i++)
        {
        }
        if (i == length)
        {
            print(s);
        }
    }

    if (num < length)
    {
        push(s, src[num]);
        dfs(s, dest, src, length, num + 1);
        r_push(s);
    }

    if (s->length >= 0)
    {
        pop(s);
        dfs(s, dest, src, length, num);
        r_pop(s);
    }
}

int main()
{
    char src[0x100], dest[0x100];
    stack s;
    memset(&s, 0, sizeof(stack));
    while ((scanf("%s %s", src, dest)) != EOF)
    {
        puts("[");
        dfs(&s, dest, src, strlen(src), 0);
        puts("]");
    }
    return 0;
}

这面这段代码来自https://blog.csdn.net/creativewang/article/details/6165574 by creativewang

/** problem name: anagrams by stack
 *  coder:mike
 *  date:2011-01-26
 *  note:我没有每一次调用都copy一份栈,因为我认为这开销太大,不过这也为我带来的很多麻烦
 *      我花了两天调试,才认识到在回溯的过程恢复初始状态的重要性。
 *      此题在输出格式上还有一些需要注意的地方,行末无空格!
 *  result: 0s,106kb,AC
 */

#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
#define STACK_SIZE 200

char source[MAX_LEN],   /**< 源字符串 */
    target[MAX_LEN],    /**< 目标字符串 */
    stack[STACK_SIZE];  /**<  栈*/
int state[2 * MAX_LEN]; /**< 每一阶段的状态,也就是路径OR解 */
int len;                /**< 字符串长度 */
int flag = 0;           /**< 标记是否有解 */

int print(int depth) /**< 输出结果 */
{
    int i = 0;
    while (i < depth - 1) /**< 这里是i<depth-1不是i<depth否则会多出空格导致WA */
    {
        if (state[i] == 1) /**< 我用1表示压栈;-1表示弹栈 */
            putchar('i');
        if (state[i] == -1)
            putchar('o');
        if (i < depth - 1) /**< ATTENTION!不是每一个后面都有空格,最后一个字符后没有! */
            putchar(' ');
        i++;
    }
    puts("");
    return 0;
}

int dfs(int depth, int npush, int npop) /**< depth:深搜的深度;npush:压栈数;npop:弹栈数 */
{
    int tmp;
    if (npush == len && npop == len) /**< 求解完成 */
    {
        flag = 1;     /**< 修改标志:有解 */
        print(depth); /**< 输出解 */
        return 0;
    }
    if (npush < len) /**< 可以压栈 */
    {
        state[depth - 1] = 1;            /**< 记录状态 */
        stack[stack[0]] = source[npush]; /**< 入栈 */
        stack[0]++;                      /**< 改变栈顶指针 */
        dfs(depth + 1, npush + 1, npop); /**< GO ON */
        stack[0]--;                      /**< 回溯要恢复栈的状态,因为不是每一次调用都复制一次栈。那样开销大 */
    }
    if (stack[0] > 0 && target[npop] == stack[stack[0] - 1]) /**< 判断是否可以弹栈,不能弹栈就回溯 */
    {
        state[depth - 1] = -1;     /**< 记录状态 */
        tmp = stack[stack[0] - 1]; /**< 因为要弹栈,所以要保存栈原来的状态 */
        stack[0]--;                /**< 改变栈顶指针 */

        dfs(depth + 1, npush, npop + 1); /**< 继续DFS */
        stack[stack[0]] = tmp;           /**< 恢复栈的状态 */
        stack[0]++;                      /**< 恢复栈顶指针 */
    }
    return 0;
}

int main(void)
{
    stack[0] = 1; /**< stack[0]指向栈顶的上一位;初始化*/
    while (scanf("%s%s", source, target) != EOF)
    {
        puts("[");
        flag = 0; /**< 初始化标志 */
        len = strlen(source);
        if (len == strlen(target)) /**< 长度不同=》跳过 */
            dfs(1, 0, 0);
        puts("]");
    }
    return 0;
}

参照大佬的代码,我又重新写了一遍:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define PUSH 1
#define POP 2
#define NONE 0
#define SIZE 0x100

void print(char *behavior, int behavior_length)
{
    int i;
    for (i = 0; i < behavior_length; i++)
    {
        if (behavior[i] == PUSH)
        {
            printf("i ");
        }
        else if (behavior[i] == POP)
        {
            printf("o ");
        }
        else
        {
            fprintf(stderr, "Error\n");
            exit(0);
        }
    }
    puts("");
}

void dfs(char *dest, char *src, char *stack, char *buf, char *behavior, int src_length, int stack_length, int buf_length, int behavior_length, int num)
{
    if (buf_length == src_length)
    {
        if (strncmp(dest, buf, src_length) == 0)
        {
            print(behavior, behavior_length);
        }
        return;
    }

    if (num < src_length)
    {
        stack[stack_length++] = src[num];
        behavior[behavior_length++] = PUSH;
        dfs(dest, src, stack, buf, behavior, src_length, stack_length, buf_length, behavior_length, num + 1);
        stack_length--;
        behavior_length--;
    }

    if (stack_length > 0)
    {
        buf[buf_length++] = stack[--stack_length];
        behavior[behavior_length++] = POP;
        dfs(dest, src, stack, buf, behavior, src_length, stack_length, buf_length, behavior_length, num);
        stack[stack_length++] = buf[--buf_length];
        behavior_length--;
    }
}

int main()
{
    char dest[SIZE], src[SIZE], stack[SIZE], buf[SIZE], behavior[SIZE];
    while (scanf("%s %s", src, dest) != EOF)
    {
        puts("[");
        dfs(dest, src, stack, buf, behavior, strlen(src), 0, 0, 0, 0);
        puts("]");
    }
    return 0;
}

说点什么

avatar
  Subscribe  
提醒