#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <cctype>
#include <cassert>
using namespace std;
const int MOD = 1e9 + 7;
// Function to check if an expression is valid
bool isValidExpression(const string& expr) {
stack<char> stk;
char lastChar = '\0';
for (char c : expr) {
if (isdigit(c)) {
if (lastChar != '\0' && isdigit(lastChar)) {
return false;
}
lastChar = c;
} else if (c == '+' || c == '-' || c == '*') {
if (lastChar == '\0' || lastChar == '+' || lastChar == '-' || lastChar == '*' || lastChar == '(') {
return false;
}
lastChar = c;
} else if (c == '(') {
stk.push(c);
lastChar = c;
} else if (c == ')') {
if (lastChar == '+' || lastChar == '-' || lastChar == '*' || lastChar == '(') {
return false;
}
if (stk.empty()) {
return false;
}
stk.pop();
lastChar = c;
} else {
return false;
}
}
return lastChar != '\0' && !isdigit(lastChar) && stk.empty();
}
// Function to evaluate the expression
long long evaluateExpression(const string& expr) {
stack<long long> values;
stack<char> ops;
auto precedence = [](char op) -> int {
if (op == '+' || op == '-') return 1;
if (op == '*') return 2;
return 0;
};
auto applyOp = [](long long a, long long b, char op) -> long long {
if (op == '+') return (a + b) % MOD;
if (op == '-') return (a - b + MOD) % MOD;
if (op == '*') return (a * b) % MOD;
return 0;
};
for (char c : expr) {
if (isdigit(c)) {
values.push(c - '0');
} else if (c == '(') {
ops.push(c);
} else if (c == ')') {
while (!ops.empty() && ops.top() != '(') {
long long val2 = values.top(); values.pop();
long long val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOp(val1, val2, op));
}
ops.pop(); // remove '('
} else if (c == '+' || c == '-' || c == '*') {
while (!ops.empty() && precedence(ops.top()) >= precedence(c)) {
long long val2 = values.top(); values.pop();
long long val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOp(val1, val2, op));
}
ops.push(c);
}
}
while (!ops.empty()) {
long long val2 = values.top(); values.pop();
long long val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOp(val1, val2, op));
}
return values.top();
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
string expr;
cin >> expr;
vector<string> operations(m);
for (int i = 0; i < m; ++i) {
int type;
cin >> type;
if (type == 1) {
int x;
char y;
cin >> x >> y;
--x; // Convert to 0-based index
expr[x] = y;
} else if (type == 2) {
int l, r;
cin >> l >> r;
--l; --r; // Convert to 0-based index
string subExpr = expr.substr(l, r - l + 1);
if (isValidExpression(subExpr)) {
cout << evaluateExpression(subExpr) << '\n';
} else {
cout << -1 << '\n';
}
}
}
return 0;
}
P5067 [Ynoi2014] 长存不灭的过去、逐渐消逝的未来该如何解决?