ZOJ1004-Anagrams by Stack

[题目来源]http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4

[题目思路]回溯法

[解题感想]在使用回溯法的过程中,用STL中的vector来记录答案,可以直接使用push_back()来保存解,这样避免了使用数组时考虑数组下标的麻烦,使用stack也有同样功效。


题中有几点需要注意,首先是结果需要按字典序排序后才能输出,我是用vector<string>保存答案,然后对vector进行排序。这里使用了STL的sort,使用方法为sort(v.begin(),v,end()),这里是升序排列,sort()参数中的less<string>() 不加也行。如果需要降序排列,就需要把less<string>()改成greater<string>()。

本题特别值得吐槽的一点是zoj的输出格式问题,一般的oj都需要把行末空格删去,在zoj里居然没有行末空格就算presentation error

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stack>
#include <vector>
#define MAXLEN 1000
using namespace std;
string src,dest;
int len;
//int op[MAXLEN];
vector<char> operation;
stack<char> st;
vector<string> ans;

void dfs(int push_cnt, int pop_cnt)
{
    if (push_cnt==len && pop_cnt==len)
    {
        string tmpstr;
        for (size_t i=0;i!=operation.size();++i)
            tmpstr+=operation[i];
        ans.push_back(tmpstr);
    }
    /*
    if (push_cnt==len && pop_cnt==len)
    {
        for (size_t i=0;i!=operation.size();++i)
            printf("%c",operation[i]);
        printf("\n");
    }*/
    if (push_cnt<len)
    {
        st.push(src[push_cnt]);
        operation.push_back('i');
        dfs(push_cnt+1,pop_cnt);
        st.pop();
        operation.pop_back();
    }
    if (pop_cnt<len && pop_cnt<push_cnt && st.top()==dest[pop_cnt])
    {
        char tmp=st.top();
        st.pop();
        operation.push_back('o');
        dfs(push_cnt,pop_cnt+1);
        st.push(tmp);
        operation.pop_back();
    }
}


int main()
{
    while (cin>>src>>dest)
    {
        len=src.size();
        ans.clear();
        printf("[\n");
        dfs(0,0);
        sort(ans.begin(),ans.end(),less<string>());
        for (size_t i=0;i!=ans.size();++i)
        {
            for (size_t j=0;j!=ans[i].size();++j)
            {
                printf("%c ",ans[i][j]);
                /*
                if (j==0)
                    printf("%c",ans[i][j]);
                else
                    printf(" %c",ans[i][j]);*/
            }
            printf("\n");
        }
        printf("]\n");
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值