破解日记-2 平面向量表达式
欢迎来到第二章,谢谢支持。
本章题目:平面向量表达式。
欢迎大家报名有道小图灵模拟赛
原方法:栈
最经典的表达式求值应用,注意处理向量也需要用到栈。
其他的就不多说了,看代码:
#include <bits/stdc++.h>
using namespace std;
#define int long long
struct node{
int a[2],type;
};
stack <node> num;
stack <char> op;
stack <int> xl;
node now,nowx;
node kk=node{{0,0},0};
const int m=1000000007;
void out(node ans){
if (ans.type==0){
while (ans.a[0]<0) ans.a[0]+=m;
cout<<ans.a[0];
}
else{
while (ans.a[0]<0) ans.a[0]+=m;
while (ans.a[1]<0) ans.a[1]+=m;
cout<<'('<<ans.a[0]<<','<<ans.a[1]<<')';
}
}
void ceil(char c){
//计算乘法
if (op.empty()) return ;
if (op.top()=='*'){
op.pop();
node n1=num.top(); num.pop();//取出数(向量)
node n2=num.top(); num.pop();
if (n1.type==0) {
if (n2.type==0){
num.push(node{{n1.a[0]*n2.a[0]%m,0LL},0LL});//都是数
}
else{
num.push(node{{n1.a[0]*n2.a[0]%m,n1.a[0]*n2.a[1]%m},1LL});//都是n2是向量
}
}
else{
if (n2.type==0){
num.push(node{{n1.a[0]*n2.a[0]%m,n1.a[1]*n2.a[0]%m},1LL});//n1是向量
}
else{
num.push(node{{(n1.a[0]*n2.a[0]+n1.a[1]*n2.a[1])%m,0LL},0LL});//全是向量
}
}
ceil(c);
}
else if (c!='*'&&op.top()!='('&&op.top()!=',') {
node n2=num.top(); num.pop();//取出数(向量)
node n1=num.top(); num.pop();
if (op.top()=='+') {
num.push(node{{(n1.a[0]+n2.a[0])%m,(n1.a[1]+n2.a[1])%m},n1.type});//只可能是加减
}
if (op.top()=='-'){
num.push(node{{(n1.a[0]-n2.a[0])%m,(n1.a[1]-n2.a[1])%m},n1.type});
}
op.pop();ceil(c);
}
else return ;
}
void go(){
while (!op.empty()&&op.top()!='('&&op.top()!=','){//寻找向量符号/左括号
ceil('+');
}
if (op.empty()) return ;
if (op.top()==','){
int tmp=xl.top(); xl.pop();
node tmpx=num.top(); num.pop();
num.push(node{{tmp,tmpx.a[0]},1LL});//保存向量的第二个值
}
op.pop();
}
signed main(){
string s;
cin>>s;s+=")";
for (int i=0; i<s.size(); i++){
char c=s[i];
if (c>='0'&&c<='9') {
now.a[0]=(now.a[0]*10+c-'0')%m;//计入数字
}
else if (c=='+'||c=='-'||c=='*'){
if (s[i-1]>='0'&&s[i-1]<='9') {
num.push(now); now=kk;//重置数字
}
ceil(c);
op.push(c);//计算
}
else if (c=='('){//计入左括号
op.push('(');
}
else if (c==','){//向量符号
if (s[i-1]>='0'&&s[i-1]<='9') {
num.push(now); now=kk;//重置数字
}
go(); op.push(',');
xl.push(num.top().a[0]);//保存第一个向量元素
num.pop();
}
else{
if (s[i-1]>='0'&&s[i-1]<='9') {
num.push(now); now=kk;//重置数字
}
go();
}
}
node ans=num.top();
out(ans);
return 0;
}
破解:函数调用
由于前面的代码过于冗长,本蒟蒻实在想优化一下
于是,我想到了使用函数!(函数不就是栈吗?!)
这里设四个函数: