C++#include<bits/stdc++.h>
using namespace std;
const int N = 2e6 + 7;
int n;
string s;
void Main(){
cin >> s;
n = s.size();
s = '0' + s;
int p = 1, d = 0, x = N;
bool flg = 0;
for(int i = 1; i <= n; i++){
for(int j = '0'; j <= '9'; j++){
int y = (max(0, j - s[i - 1]) + (i == n ? 0 : max(0, s[i + 1] - j))) - ((max(0, s[i] - s[i - 1]) + (i == n ? 0 : max(0, s[i + 1] - s[i]))));
if(y < x){
p = i, d = j, x = y;
flg = 1;
}
}
}
if(flg) s[p] = d;
for(int i = 1; i <= s[1] - '0'; i++) cout << '(';
cout << s[1];
for(int i = 2; i <= n; i++){
if(s[i] <= s[i - 1]){
for(int j = 1; j <= s[i - 1] - s[i]; j++) cout << ')';
cout << s[i];
}
else{
for(int j = 1; j <= s[i] - s[i - 1]; j++) cout << '(';
cout << s[i];
}
}
for(int i = 1; i <= s[n] - '0'; i++) cout << ')';
cout << '\n';
}
int main(){
freopen("bracket.in", "r", stdin);
freopen("bracket.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0);
int Task;
cin >> Task;
while(Task--) Main();
return 0;
}
C++#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int M = 26, V = 1e5 + 7, N = V << 1;
int n;
int m[2], q;
ll p;
ll a[2][M], b[2][M];
int nxt[N][40];
ll fpow(ll x, ll y){
ll sum = 1;
while(y){
if(y & 1) sum = sum * x % p;
x = x * x % p;
y >>= 1;
}
return sum;
}
void Build(){
for(int j = 1; j <= 30; j++){
for(int i = 0; i < n; i++){
nxt[i][j] = nxt[nxt[i][j - 1]][j - 1];
}
}
}
int main(){
freopen("poly.in", "r", stdin);
freopen("poly.out", "w", stdout);
ios::sync_with_stdio(0);
cin.tie(0);
cin >> m[0] >> m[1] >> q >> p;
for(int j = 0; j < 2; j++){
for(int i = 1; i <= m[j]; i++){
cin >> a[j][i] >> b[j][i];
}
}
for(int j = 0; j < 2; j++){
for(int w = 0; w < p; w++){
ll sum = 0;
for(int i = 1; i <= m[j]; i++){
sum = (sum + a[j][i] * fpow(w, b[j][i]) % p) % p;
}
nxt[w + j * p][0] = sum + (j ^ 1) * p;
}
}
n = 2 * p;
Build();
while(q--){
int x, y, s;
cin >> x >> y >> s;
x = x % p + s * p;
for(int i = 30; i >= 0; i--){
if(y >= (1 << i)){
x = nxt[x][i];
y -= (1 << i);
}
}
printf("%d\n", x % p);
}
return 0;
}