-
表达式树的建立
-
递归计算的熟练使用
-
递归建树,
map
优化
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#pragma GCC optimize(2)
typedef long long ll;
using namespace std;
const int Mod = 1e9 + 7;
struct Node {
Node* left;
Node* right;
string item;
Node() : left(nullptr), right(nullptr), item("") {}
};
bool isOp(string s) {
return (s == "*") || (s == "-") || (s == "+");
}
void dfs(Node* root, vector<string>& items, int& cnt) {
if (cnt < 0) {
return;
}
string tmp = items[cnt];
root -> item = tmp;
cnt--;
if (!isOp(tmp)) {
return;
}
root->left = new Node(); root->right = new Node();
dfs(root->right, items, cnt);
dfs(root->left, items, cnt);
}
Node* build(vector<string> items) {
Node* root = new Node();
int cnt = items.size()-1;
dfs(root, items, cnt);
return root;
}
ll cal(Node* root, map<string, ll>& value) {
if (root->item == "*") {
return (cal(root->left, value)%Mod * cal(root->right, value)%Mod)%Mod;
} else if (root->item == "-") {
return (cal(root->left, value)%Mod - cal(root->right, value)%Mod)%Mod;
} else if (root->item == "+") {
return (cal(root->left, value)%Mod + cal(root->right, value)%Mod)%Mod;
} else if (root->item[0] == 'x') {
return value[root->item]%Mod;
} else {
return stoi(root->item)%Mod;
}
return 0;
}
ll p_cal(Node* root, map<string, ll>& p_value, map<string, ll>& value) {
if (root->item == "*") {
return (p_cal(root->left, p_value, value)%Mod * cal(root->right, value)%Mod +
p_cal(root->right, p_value, value)%Mod * cal(root->left, value)%Mod)%Mod;
} else if (root->item == "-") {
return (p_cal(root->left, p_value, value)%Mod - p_cal(root->right, p_value, value)%Mod)%Mod;
} else if (root->item == "+") {
return (p_cal(root->left, p_value, value)%Mod + p_cal(root->right, p_value, value)%Mod)%Mod;
} else if (root->item[0] == 'x') {
return p_value[root->item]%Mod;
} else {
return 0;
}
return 0;
}
int main () {
int n, m; cin >> n >> m; getchar();
string line, token;
getline(cin, line);
istringstream iss(line);
vector<string> items;
while (iss >> token) items.push_back(token);
Node* root = build(items);
for (int i = 0; i < m; ++i) {
int x; cin >> x;
map<string, ll> value;
map<string, ll> p_value;
for (int i = 1; i <= n; ++i) {
string str = "x" + to_string(i);
int val; cin >> val;
value[str] = val;
if (i == x) p_value[str] = 1;
else p_value[str] = 0;
}
cout << (p_cal(root, p_value, value) + Mod)%Mod << endl;
}
return 0;
}