在本题中我使用如下代码会 RE:
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
#define int long long
const int N = 200005;
const int mod = 10007;
int n,top,cnt = 0;
string st;
string s;
struct node
{
int a,b;
} num[N];
node operator+(node x,node y)
{
return (node){x.a * y.a % mod, (x.a * y.b % mod + x.b * y.a % mod + x.b * y.b % mod) % mod};
}
node operator*(node x,node y)
{
return (node){(x.a * y.a % mod + x.a * y.b % mod + x.b * y.a % mod) % mod, x.b * y.b % mod};
}
node calc(node x,char op,node y)
{
// cout << x.a << " " << x.b << " " << y.a << " " << y.b << endl;
if(op == '+') return x + y;
if(op == '*') return x * y;
}
int priority(char op)
{
if(op == '(') return 1;
if(op == ')') return 2;
if(op == '+') return 3;
if(op == '*') return 4;
return -1;
}
signed main()
{
cin >> n;
cin >> st;
st = '(' + st + ')';
for(int i=0;i<st.size();i++)
{
if(st[i] == '(') s[++top] = st[i];
else
{
while(priority(s[top]) >= priority(st[i]))
{
// cout << "---" << endl;
node y = num[cnt--];
node x = num[cnt--];
char op = s[top--];
num[++cnt] = calc(x,op,y);
}
if(st[i] == ')') top--;
else s[++top] = st[i];
}
// for(int j=1;j<=cnt;j++) cout << "a " << num[j].a << ",b " << num[j].b << ",j " << j << ",cnt " << cnt << endl;
if(st[i] != ')' && st[i+1] != '(')
{
// cout << "mmm" << endl;
num[++cnt] = (node){1,1};
// cout << cnt << endl;
}
}
cout << num[1].a % mod << endl;
return 0;
}
但是我把字符串 s 改为字符数组后就过了,也就是如下代码:
#include<iostream>
#include<cmath>
#include<cstring>
using namespace std;
#define int long long
const int N = 200005;
const int mod = 10007;
int n,top,cnt = 0;
string st;
char s[N];
struct node
{
int a,b;
} num[N];
node operator+(node x,node y)
{
return (node){x.a * y.a % mod, (x.a * y.b % mod + x.b * y.a % mod + x.b * y.b % mod) % mod};
}
node operator*(node x,node y)
{
return (node){(x.a * y.a % mod + x.a * y.b % mod + x.b * y.a % mod) % mod, x.b * y.b % mod};
}
node calc(node x,char op,node y)
{
// cout << x.a << " " << x.b << " " << y.a << " " << y.b << endl;
if(op == '+') return x + y;
if(op == '*') return x * y;
}
int priority(char op)
{
if(op == '(') return 1;
if(op == ')') return 2;
if(op == '+') return 3;
if(op == '*') return 4;
return -1;
}
signed main()
{
cin >> n;
cin >> st;
st = '(' + st + ')';
for(int i=0;i<st.size();i++)
{
if(st[i] == '(') s[++top] = st[i];
else
{
while(priority(s[top]) >= priority(st[i]))
{
// cout << "---" << endl;
node y = num[cnt--];
node x = num[cnt--];
char op = s[top--];
num[++cnt] = calc(x,op,y);
}
if(st[i] == ')') top--;
else s[++top] = st[i];
}
// for(int j=1;j<=cnt;j++) cout << "a " << num[j].a << ",b " << num[j].b << ",j " << j << ",cnt " << cnt << endl;
if(st[i] != ')' && st[i+1] != '(')
{
// cout << "mmm" << endl;
num[++cnt] = (node){1,1};
// cout << cnt << endl;
}
}
cout << num[1].a % mod << endl;
return 0;
}
有没有大佬能解释一下为什么使用字符串会 RE?
悬 5 关。