[题目来源]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;
}