P14339 [JOI2020 预选赛 R2] 剪刀石头布 / Rock-Scissors-Paper Expression 题解
思路
题目传送门,将运算时的每一个元素设一个三元组状态 表示这一个元素为 、、 的方案数,则初始 、、、。对于 与 进行的三种运算规则为:
其中 、 不满足结合律,即 ,所以要严格要求从左往右计算。根据运算要求转化为后缀表达式求解(不转也行),最后输出目标结果对应答案三元组中的方案数即可。
#include<bits/stdc++.h> //我爱万能头
using namespace std;
#define int long long
const int Mod=1e9+7;
struct Node{
int r,s,p;
}a,b,ans;
int n;
string s;
char c,ch;
stack<Node>res;
stack<char>opt;
Node calc(Node a,Node b,char ch){ //+、-、*运算
Node res={0,0,0};
if(ch=='+'){
(res.r=(a.r*b.r)%Mod+(a.r*b.s)%Mod+(a.s*b.r)%Mod)%=Mod;
(res.s=(a.s*b.s)%Mod+(a.s*b.p)%Mod+(a.p*b.s)%Mod)%=Mod;
(res.p=(a.p*b.p)%Mod+(a.r*b.p)%Mod+(a.p*b.r)%Mod)%=Mod;
}
if(ch=='-'){
(res.r=(a.r*b.r)%Mod+(a.r*b.p)%Mod+(a.p*b.r)%Mod)%=Mod;
(res.s=(a.s*b.s)%Mod+(a.r*b.s)%Mod+(a.s*b.r)%Mod)%=Mod;
(res.p=(a.p*b.p)%Mod+(a.s*b.p)%Mod+(a.p*b.s)%Mod)%=Mod;
}
if(ch=='*'){
(res.r=(a.r*b.r)%Mod+(a.s*b.p)%Mod+(a.p*b.s)%Mod)%=Mod;
(res.s=(a.s*b.s)%Mod+(a.r*b.p)%Mod+(a.p*b.r)%Mod)%=Mod;
(res.p=(a.p*b.p)%Mod+(a.r*b.s)%Mod+(a.s*b.r)%Mod)%=Mod;
}
return res;
}
signed main(){
cin>>n;
cin>>s;
cin>>c;
s='('+s+')'; //这样好像可以确保运算完全
for(int i=1;i<=n+1;i++){
if(s[i]=='R'){
res.push({1,0,0});
}
if(s[i]=='S'){
res.push({0,1,0});
}
if(s[i]=='P'){
res.push({0,0,1});
}
if(s[i]=='?'){
res.push({1,1,1});
}
if(s[i]=='+'){
while(!opt.empty()){
ch=opt.top();
if(ch=='('){
break;
}
opt.pop();
a=res.top();
res.pop();
b=res.top();
res.pop();
res.push(calc(a,b,ch));
}
opt.push('+');
}
if(s[i]=='-'){
while(!opt.empty()){
ch=opt.top();
if(ch=='('){
break;
}
opt.pop();
a=res.top();
res.pop();
b=res.top();
res.pop();
res.push(calc(a,b,ch));
}
opt.push('-');
}
if(s[i]=='*'){
while(!opt.empty()){
ch=opt.top();
if(ch!='*'){
break;
}
opt.pop();
a=res.top();
res.pop();
b=res.top();
res.pop();
res.push(calc(a,b,ch));
}
opt.push('*');
}
if(s[i]=='('){
opt.push('(');
}
if(s[i]==')'){
while(!opt.empty()){
ch=opt.top();
opt.pop();
if(ch=='('){
break;
}
a=res.top();
res.pop();
b=res.top();
res.pop();
res.push(calc(a,b,ch));
}
}
}
ans=res.top();
if(c=='R'){
cout<<ans.r;
}
if(c=='S'){
cout<<ans.s;
}
if(c=='P'){
cout<<ans.p;
}
return 0; //完结撒花
}