思路是带入 x=1,0 后求出 k,b。
#include <bits/stdc++.h>
#define int long long
using namespace std;
int Mod, P;
string s;
stack <int> num;
stack <char> t;
int cal() {
int y = num.top(); num.pop();
int x = num.top(); num.pop();
char op = t.top(); t.pop();
if (op == '+') return (x + y) % Mod;
if (op == '-') return (x - y + Mod) % Mod;
if (op == '*') return x * y % Mod;
}
int level(char x) {
if (x == '+' || x == '-') return 1;
if (x == '*') return 2;
return -1;
}
int work(int x) {
while (!num.empty()) num.pop();
while (!t.empty()) t.pop();
int n = s.size(), now = 0;
for (int i = 0; i < n; i++) {
if (s[i] >= '0' && s[i] <= '9') {
now = (now * 10 % Mod + (s[i] - '0')) % Mod;
if (i == n - 1 || (s[i + 1] < '0' || s[i + 1] > '9'))
num.push(now);
now = 0;
}
else if (s[i] == 'x') num.push(x);
else if (s[i] == '(') t.push(s[i]);
else if (s[i] == ')') {
while (!t.empty() && t.top() != '(') num.push(cal());
t.pop();
}
else {
while (!t.empty() && level(t.top()) >= level(s[i])) num.push(cal());
t.push(s[i]);
}
}
while (!t.empty()) num.push(cal());
return num.top();
}
signed main() {
string S;
cin >> S >> P >> Mod;
s = S; int b = work(0);
s = S; int k = (work(1) - b + Mod) % Mod;
for (int i = 0; i <= Mod; i++)
if ((k * i % Mod + b) % Mod == P)
return cout << i, 0;
return 0;
}