#include<bits/stdc++.h>
#include<stack>
#include<vector>
using namespace std;
string a, b;
int length;//a的长度
stack<char>build;//工具栈(与 b 比)
vector<char>operate;//存放符号"i" "o"
//目标元素构造完毕,输出操作序列 operate[](条件:出入栈操作的次数等于源单词的长度)
void dfs(int iPush, int iPop) {
if(iPush == length&&iPop == length) {
for(int i = 0; i < operate.size(); i++){//operate.size():op数组的实际长度
cout<<operate[i]<<" ";
}
cout<<endl;
}
if(iPush + 1 <= length){
build.push(a[iPush]);//.push() 进栈(栈顶元素)
operate.push_back('i');//尾部加入一个数据
dfs(iPush + 1, iPop);//转折
build.pop();//出栈(删除栈顶元素)
operate.pop_back();//删除末尾元素
}
if(iPop + 1 <= iPush&&iPop + 1 <= length&&build.top() == b[iPop]){
char tc = build.top();//栈顶元素
build.pop();
operate.push_back('o');
dfs(iPush, iPop + 1);//转折
build.push(tc);
operate.pop_back();
}
}
int main() {
while(cin>>a>>b) {
length = a.length();
cout<<"["<<endl;
dfs(0, 0);
cout<<"]"<<endl;
}
return 0;
}
ZOJ-1094 Matrix Chain Multiplication题目
//#include<bits/stdc++.h>
#include<iostream>
#include<stack>
#include<map>
using namespace std;
int n;//矩阵个数
char name;//矩阵名字
struct Node {//结构体
int row, col;//矩阵行列
};
stack<Node> array;//栈_模拟乘法
map<char, Node> matrix;//映射 _模拟矩阵
string exp;//输入的运算式(字符)
int main() {
cin>>n;//矩阵数目
for(int i = 0; i < n; i++) {
cin>>name;//键
cin>>matrix[name].row>>matrix[name].col;//matrix[name]是键,matrix[name].row/col是值 (比一般的特殊有两个)
}
//读取
while(cin>>exp) {
int i;
int count = 0;
for(i = 0; i < exp.size(); i++) {
if(exp[i] == '(') {
continue;
}
if(exp[i] == ')') {
Node b = array.top();
array.pop();
Node a = array.top();
array.pop();
if(a.col != b.row) {//column列 row行
cout<<"error"<<endl;
break;
}
//相乘次数
count += a.row * b.row * b.col;
//新矩阵入栈
Node tmp = {a.row, b.col};
array.push(tmp);
} else array.push(matrix[exp[i]]);
}
if(i == exp.size()) {
cout<<count<<endl;
}
}
return 0;
}