区间dp, dp[ i ][ j ]表示第 i 个括号到第 j 个括号之间的所有括号能不能形成一个合法方案。
然后dp就完事了。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ull unsigned long long using namespace std; const int N = 600 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; int f[N][N]; int path[N][N]; int n, L[N], R[N]; char ans[N << 1]; int dp(int i, int j) { if(i > j) return true; if(~f[i][j]) return f[i][j]; if(i == j) return L[i] <= 1 && R[i] >= 1; f[i][j] = false; for(int k = i; k <= j; k++) { if(2 * (k - i) + 1 < L[i] || 2 * (k - i) + 1 > R[i]) continue; if(dp(i + 1, k) && dp(k + 1, j)) { f[i][j] = true; path[i][j] = k - i; break; } } return f[i][j]; } void print(int i, int j, int start, int cnt) { if(i > j) return; ans[start] = '('; ans[start + cnt * 2 + 1] = ')'; print(i + 1, i + cnt, start + 1, path[i + 1][i + cnt]); print(i + cnt + 1, j, start + 2 * cnt + 2, path[i + cnt + 1][j]); } int main() { memset(f, -1, sizeof(f)); scanf("%d", &n); ans[2 * n + 1] = '\0'; for(int i = 1; i <= n; i++) scanf("%d%d", &L[i], &R[i]); if(!dp(1, n)) puts("IMPOSSIBLE"); else { print(1, n, 1, path[1][n]); puts(ans + 1); } return 0; } /* */