【算法】算法之美—Anagrams by Stack

ZOJ1004-Anagrams by Stack(回溯) 如何根据一系列堆栈的操作实现回文构词法呢?有两种堆栈的操作,将单词TROT转换成TORT。 阅读详情

题目概述:Anagrams by Stack

  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

]



简单描述


输入要求

  输入由多行组成,每对单词占2行。第1行为原始单词(不包括行尾的换行符),第2行为目标单词(同样不包括行尾的换行符)。

输出要求

  对于输入的每一对字符串,你的程序应该按顺序生成所有的有效的进出栈操作列表,其中的每组操作都能使原字符串转变为目标字符串。每一组操作要由方括号括起来,其中i表示压入,o表示弹出。

程序要求

  可能有多组有效操作都能够为输入的单词生成指定的字母排列。比如对于输入的单词“FOO”,操作i i o i o o就可以生成重排的单词“OOF”。操作i i i o o o也可以生成同样的重排。你要写一个程序,找出所有有效的操作序列,以使输入的一对单词的前者重排为后者。



题目分析

  这道题必须遍历所有可能的进出栈序列才能求得全部解。因此同Crashing Balloon解法一样,属于DFS(深度优先搜索)加回溯。



解题算法

  注释相当完整,如题

#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解,状态1表示压栈;-1表示弹栈 */
int len;                    /* 字符串长度 */
int flag=0;                 /* 标记是否有解 */
               
int print(int depth)        /* 输出结果 */
{
    int i=0;
    while(i<depth-1)        /* 这里是i<depth-1不是i<depth否则会多出空格 */
    {
        if(state[i]==1)     /* 用1表示压栈;-1表示弹栈 */
            putchar('i');
        if(state[i]==-1)
            putchar('o');
        if(i<depth-1)       /* ATTENTION!不是每一个后面都有空格,最后一个字符后没有! */
            putchar(' ');
        i++;
    }
    putchar('\n');
    return 0;
}
               
int dfs(int depth,int npush,int npop)       /* depth:深搜的深度;npush:压栈数;npop:弹栈数 */
{
    if(npush==len&&npop==len)               /* 求解完成 */
    {
        flag=1;                             /* 修改标志:有解 */
        print(depth);                       /* 输出解 */
        return 0;
    }
    if(npush<len)                           /* 可以压栈 */
    {
        state[depth-1]=1;                   /* 记录状态,1表示入栈 */
        stack[stack[0]]=source[npush];      /* 入栈,将源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;              /* 记录状态, -1表示弹栈 */
        int tmp=stack[stack[0]-1];      /* 因为要弹栈,所以要保存栈原来的状态,tmp记录的是栈顶的位置 */
        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;
}





本文出自 “成鹏致远” 博客,请务必保留此出处http://infohacker.blog.51cto.com/6751239/1198026

服务器被矿工入侵记录 一次服务器被矿工入驻的处理记录 阅读详情

相关推荐

使用ONNX Runtime在Java Web应用中部署深度学习模型

当应用场景需要集成深度学习模型进行推理时,直接在Java Web应用中集成深度学习框架可能会面临性能、兼容性等问题。为了将深度学习模型无缝集成到Java Web应用中,是一项广受认可且实用的方法。本篇文档将介绍如何将模型转换为ONNX格式,并通过ONNX Runtime Server进行部署,并通过Java Web应用调用以进行回归或预测任务。本方案的主要目标是实现以下功能:将PyTorch模型转换为ONNX格式。部署ONNX Runtime Server,加载ONNX模型并提供推理服务。

shysea2019的博客 8860

数据结构5 栈和队列

若用一个大小为6的数组来实现循环队列,且当前rear和front的值分别为0和3,当从队列中删除一个元素,再加入两个元素后,rear和front的值分别为( )在堆栈S上运行以下操作:Push(S,1)、Push(S,2)、Pop(S)、Push(S,3)、Pop(S)和Pop(S)。如果按顺序{1,2,3,4,5}将键推到堆栈上,则不可能获得输出序列{3,4、1,2、5}。设一数列的顺序为1,2,3,4,5,6,通过队列操作可以得到( )的输出序列。给定堆栈的弹出顺序为{1,2,3,4,5,6}。

ohuojiuwo的博客 2398

如何使用AKShare作为OpenBB的数据源

`openbb_akshare`项目是 OpenBB 的数据源扩展。可以用于查询A股和港股数据

FinAnalyzer金融分析工具 3198

ZOJ1004-Anagrams by Stack

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

Dante__Alighieri的专栏 1765

Python爬虫实战:5分钟搞定Boss直聘数据抓取(附完整代理IP配置)

本文详细介绍了如何使用Python爬虫高效抓取Boss直聘的招聘数据,包括环境配置、反爬策略、数据采集与存储、数据分析等完整流程。通过实战案例,帮助开发者快速掌握招聘市场数据抓取技术,为职业决策提供数据支持。

weixin_30832143的博客 354

使用DeepSeek、MCP和AKShare实现智能金融问答系统技术方案

DeepSeek是由深度求索公司开发的大规模语言模型,最新版本DeepSeek-V3采用混合专家(MoE)架构,拥有671B参数,激活37B参数,在多项基准测试中表现优异3。要使用DeepSeek的API服务:访问DeepSeek平台注册账号获取API Key(形如AKShare是基于Python的金融数据接口库,提供股票、基金、期货、宏观经济等领域的海量数据。主要特点包括:免费开源,数据源丰富支持多种数据格式(DataFrame/JSON)持续更新维护安装命令。

Kin 3186

UVa732 - Anagrams by Stack(DFS)

How can anagrams result from sequences of stack operations? There are twosequences 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 a

多看多听多总结 1299

基于线性光耦HCNR200的高压直流采样电路设计与精度优化

本文详细介绍了基于线性光耦HCNR200的高压直流采样电路设计与精度优化方法。针对直流高电压测量中的安全与干扰问题,提出采用HCNR200光耦隔离方案,实现高精度线性传输。文章深入解析电路设计关键细节,包括电阻网络、运放选型、滤波电容配置等,并提供精度优化实战技巧与常见问题排查指南,助力新能源电动汽车和高压储能系统的高压直流采样应用。

weixin_42713608的博客 587

ZOJ1004Anagrams by Stack

Anagrams by Stack Time Limit: 2000 msMemory 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 ] whereistands for ..

Lycodeboy的博客 291

MobaXterm详细使用教程

当然MobaXterm的功能远不止这些,但这些是最基本,最常用的,因此先拿出来讲。点击确定后,输入密码(输入密码时并不会显示,只管输入后按确定即可,第一次登陆成功后会提示保存密码,一般选择同意),就可以连接上虚拟机了。(2) 我们可以直接apt-get安装vim等常用功能(或者官网下载插件),实现在windows下模拟linux环境,这样就可以使用vi命令准备INCAR文件,也可以使用Gnuplot进行绘图。支持 Unix 命令(bash,ls,cat,sed,grep,awk,rsync,…

博客 4万+

WOFOST作物模型(3):敏感性分析

使用TAGP(Total Above Ground Production),地上总产量TSUM1,temperature sum from emergence to anthesis,萌发至开花所需温度TSUM2,temperature sum from anthesis to maturity,开花至成熟所需温度SPAN,life span of leaves growing at 35 Celsius,生长温度为35度时的叶龄。

所有专家都曾始于新手 1148

【Acm】算法之美—Anagrams by Stack

题目概述:Anagrams by Stack     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...

weixin_33712881的博客 245

极智芯 | 解读国产CPU之海光

大家好,我是极智视界,本文分享一下 解读国产CPU之海光。希望我的分享能对你的学习有一点帮助。

极智视界 3326

Anagrams by Stack

// DJ.W 2013.4.20 //问题描述 : Anagrams by Stack // http://acm.suse.edu.cn/index.php?mod=problem&id=1056 //算法思路: 用回溯法搜索 //开发环境: vs2008 #include "stdafx.h" #include using namespace std; #include #i

WUDAIJUN的博客 1198

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

zoj1004 Anagrams by Stack

Anagrams by Stack Time Limit: 2000MS   Memory Limit: 65536KB   64bit IO Format: %lld & %llu Submit Status Description How can anagrams result from sequences of stack oper

acm_1361677193的专栏 475

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

zoj1004-Anagrams by Stack

zoj1004 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1004

lvy的专栏 933

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

anagrams by stack C 题解

anagrams by stacks, dfs,回溯,zoj-1004

Mr. WA's Blog 2715

回溯算法之Anagrams by Stack

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 ] wher

hqf1992的专栏 700

ZOJ 1004 Anagrams by Stack 分析与解答

问题: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 oi o i i o o i o]where i stand

the Pensieve 4464

Anagrams by Stack python

def dst(push, pop, olst, dlst, s, t): #global result l = len(olst) if push==l and pop==l: print t return 0 if len(s)==0: s.append(olst[push]) push

Json_Nie的专栏 790

ZOJ 1004 Anagrams by Stack

原题:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1004 题目太长了。。。其实很简单 就是能不能把一个字符串 比如:madam 通过栈操作,变成adamm     Sample Input madam adamm     Sample Output [ i i i i o o o i o o...

夜很美 232
上一篇: 【ARM】s3c2440裸机实现图片显示
下一篇: 【C/C++】程序如何来,编译全过程
成鹏致远
博客等级 码龄14年 50粉丝 132原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址