JXUST-OJ 广告位招租 K: Keep patient (搜索)
K: Keep patient
题意:给你一个长度小于14的字符串,输出所有出栈顺序。
分析:搜索即可,每次分为出栈入栈两种选择,这个题一定不能用c++输出,不然会超时,加速也没用。
两个版本dfs, bfs,
dfs的
#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define d(x) cout << (x) << endl
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int N = 20;
set<string> st;
int len;
char a[N];
char stk[N];
void dfs(int in, int out, string str) //in代表几个字符进过栈了
{ //out代表现在栈里还有几个字符
if(in == len && out == 0){ //str代表当前出栈字符串
st.insert(str);
return;
}
if(in < len){
char c = stk[out];
stk[out] = a[in];
dfs(in + 1, out + 1, str);
stk[out] = c; //回溯
}
if(out > 0){
string str1 = str + stk[out-1];
dfs(in, out - 1, str1);
}
}
int main()
{
scanf("%s", a);
len = strlen(a);
dfs(0, 0, "");
cout << st.size() << endl;
for(auto x : st){
printf("%s\n", x.c_str());
}
return 0;
}
bfs的
#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define d(x) cout << (x) << endl
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int N = 20;
set<string> st;
char a[N];
int len;
struct node{
int in; //当前in个字符以进栈
char s[N] = {0}; //数组s模拟栈
int top;
string ans; //当前出栈字符串
node(int in1, const char * s1, int top1, string ans1){
in = in1;
strcpy(s, s1);
top = top1;
ans = ans1;
}
};
void bfs()
{
queue<node> q;
q.push(node(0, "", 0, ""));
while(!q.empty()){
node cnt = q.front();
q.pop();
if(cnt.in < len){
char ss[N] = {0};
strcpy(ss, cnt.s);
ss[cnt.top] = a[cnt.in];
q.push(node(cnt.in + 1, ss, cnt.top + 1, cnt.ans));
}
if(cnt.top > 0){
string aa = cnt.ans + cnt.s[cnt.top - 1];
q.push(node(cnt.in, cnt.s, cnt.top - 1, aa));
}
if(cnt.in == len && cnt.top == 0){
st.insert(cnt.ans);
}
}
}
int main()
{
scanf("%s", a);
len = strlen(a);
bfs();
cout << st.size() << endl;
for(auto x : st){
printf("%s\n", x.c_str()); //不能用cout
}
return 0;
}