蓝桥杯训练题No.4

ZOJ-1004 Anagrams by Stack题目

#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; 
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值