AcWing 5299. 梯度求解
原题链接
中等
作者:
我爱鸡仔
,
2024-11-29 16:15:40
,
所有人可见
,
阅读 6
EASY MONEY!!!
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stack>
#include <sstream>
using namespace std;
typedef long long LL;
const int N = 1100, MOD = 1e9 + 7;
int n, m;
int k;
int e[N];
string f[N];
int fx[N], dfdx[N], h1 = -1, h2 = -1;
char op[N], h3 = -1;
//stack<int> fx, dfdx;
//stack<char> op;
void eval_adf()
{
LL db = dfdx[h2]; h2 -- ;
LL da = dfdx[h2]; h2 -- ;
LL b = fx[h1]; h1 -- ;
LL a = fx[h1]; h1 -- ;
char c = op[h3]; h3 -- ;
int y, dy;
if ( c == '+' ) {
y = (a + b) % MOD;
dy = (da + db) % MOD;
}
else if ( c == '-' ) {
y = (a - b) % MOD;
dy = (da - db) % MOD;
}
else {
y = (a * b) % MOD;
dy = (da * b + db * a) % MOD;
}
dfdx[ ++ h2] = dy;
fx[ ++ h1] = y;
}
int main()
{
cin >> n >> m;
cin.get();
string ss;
getline(cin, ss);
stringstream ssin;
ssin << ss;
int len = 0;
string temp;
while (ssin >> temp) f[len ++ ] = temp;
while (m -- ) {
cin >> k;
for ( int i = 1; i <= n; i ++ )
cin >> e[i];
for ( int i = 0; i < len; i ++ ) {
string c = f[i];
if ( c[0] == 'x') {
int idx = stoi(c.substr(1));
if ( idx != k ) {
fx[ ++ h1] = e[idx];
dfdx[ ++ h2] = 0;
} else {
fx[ ++ h1] = e[idx];
dfdx[ ++ h2] = 1;
}
}
else if ( (c[0] == '-' && c.size() > 1) || isdigit(c[0]) ) {
int sum = stoi(c);
fx[ ++ h1] = sum;
dfdx[ ++ h2] = 0;
}
else {
op[ ++ h3] = c[0];
eval_adf();
}
}
while ( h3 > -1 ) eval_adf();
cout << ((dfdx[h2] % MOD) + MOD) % MOD<< endl;
}
return 0;
}