题目链接: http://118.190.20.162/view.page?gpid=T173
参考代码:
#include <bits/stdc++.h>
using i64 = long long;
constexpr int P = int(1e9) + 7;
int add(int a, int b) {
int c = a + b;
if (c >= P)
c -= P;
if (c < 0)
c += P;
return c;
}
struct Node {
Node *l = nullptr;
Node *r = nullptr;
virtual int getDer(const std::vector<int> &a, int derId) const = 0;
virtual int getVal(const std::vector<int> &a) const = 0;
};
struct InNode : public Node {
const char opt;
InNode(char c) : opt{c} {}
int getDer(const std::vector<int> &a, int derId) const {
int leftDer = this->l->getDer(a, derId);
int rightDer = this->r->getDer(a, derId);
if (opt == '+')
return add(leftDer, rightDer);
if (opt == '-')
return add(leftDer, -rightDer);
if (opt == '*') {
int leftVal = this->l->getVal(a);
int rightVal = this->r->getVal(a);
return (1ll * leftDer * rightVal + 1ll * leftVal * rightDer) % P;
}
return 0;
}
int getVal(const std::vector<int> &a) const {
int leftVal = this->l->getVal(a);
int rightVal = this->r->getVal(a);
if (opt == '+')
return add(leftVal, rightVal);
if (opt == '-')
return add(leftVal, -rightVal);
if (opt == '*')
return 1ll * leftVal * rightVal % P;
return 0;
}
};
struct Leaf : public Node {};
struct Constant : public Leaf {
const int data;
Constant(int data) : data{data} {}
int getDer(const std::vector<int> &a, int derId) const {
return 0;
}
int getVal(const std::vector<int> &a) const {
return data;
}
};
struct Variable : public Leaf {
const int id;
Variable(int id) : id{id} {}
int getDer(const std::vector<int> &a, int derId) const {
return id == derId;
}
int getVal(const std::vector<int> &a) const {
return a[id];
}
};
Node *build(const std::string &sufExpr) {
std::stringstream stream{sufExpr};
std::stack<Node *> stack;
std::string tmp;
while (stream >> tmp) {
/*** InNode ***/
if (tmp == "-" or tmp == "+" or tmp == "*") {
Node *p = new InNode{tmp[0]};
p->r = stack.top();
stack.pop();
p->l = stack.top();
stack.pop();
stack.push(p);
}
/*** Leaf ***/
else {
auto getDigit = [&](const std::string &s) -> int {
int x = std::stol(s);
return add(x, 0);
};
Node *p = nullptr;
if (tmp[0] == 'x') {
p = new Variable(getDigit(tmp.substr(1)) - 1);
} else {
p = new Constant(getDigit(tmp));
}
stack.push(p);
}
}
return stack.top();
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int n, qn;
std::cin >> n >> qn;
std::cin.get();
std::string expr;
std::getline(std::cin, expr);
Node *root = build(expr);
std::vector<int> a(n);
int derId;
while (qn--) {
std::cin >> derId;
derId -= 1;
for (int i = 0; i < n; i++) {
std::cin >> a[i];
a[i] = add(a[i], 0);
}
int res = root->getDer(a, derId);
std::cout << res << '\n';
}
return 0;
}