您的位置:首页 > 其它

ZOJ 1004 Anagrams by Stack

2016-12-05 20:55 246 查看
题意:对于给定的两个字符串,通过栈,将字符串a变成字符串b,要找字典序输出所有的操作方法。

思路 :比较明显的是操作有两种:随时都可以入栈,或当栈顶和目前指向的b串匹配的时候此时还能够出栈。每次完成dfs需要把状态恢复。

开始的时候想多了,结果越写越长。。

#include <cstdio>
#include <string>
#include<iostream>
#include<vector>
#include <stack>
#include <queue>
#include <map>
#include <cstdlib>
#include<string.h>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <set>

using namespace std;

typedef long long ll;
typedef pair<int, int>pii;
typedef pair<ll, ll> pll;
typedef pair<int, ll> pil;
typedef vector<vector<ll> >vvi;
typedef vector<ll> vi;

const int MAXN = 300000 + 10;

int ca[50], cb[50];
int t[3000],top;
int ans[3000],tot;
string a, b;

void print(int x,int y)
{
for (int i = 0; i < x + y; i++)
{
printf("%c ", ans[i] ? 'i' : 'o');
}
printf("\n");
}

void dfs(int x,int y)
{
if (x == a.size() && y == a.size())
{
print(x, y);
return;
}
if (x < a.size())
{
ans[tot++] = 1;
t[top++] = a[x];
dfs(x + 1, y);
top--;
tot--;
}
if (top&&t[top - 1] == b[y])
{
int tmp = t[top - 1];
top--;
ans[tot++] = 0;
dfs(x, y + 1);
tot--;
t[top++] = tmp;
}
}

int main()
{
while (cin >> a >> b)
{
memset(ca, 0, sizeof ca);
memset(cb, 0, sizeof cb);
for (int i = 0; i < a.size(); i++)ca[a[i] - 'a']++;
for (int i = 0; i < b.size(); i++)cb[b[i] - 'a']++;
int flag = 1;
for (int i = 0; i < 26; i++)if (ca[i] != cb[i])flag = 0;
tot = 0; top = 0;
int ans = 0;
printf("[\n");
if (flag)dfs(0, 0);
printf("]\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: