题意:给出n个区间,每个区间表示右括号距离左括号的距离范围,输出符合条件的括号序列,若没有,输出IMPOSSIBLE。
题解:贪心
用栈存未写上的右括号,判断当前位置是否满足区间要求,贪心让每个右括号尽可能往左靠,若栈中仍有右括号,则说明不存在这样的序列。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
int n, l[666], r[666], num;
stack<pair<int, int> > s;
string ss;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d%d", &l[i], &r[i]);
num = 1;
for (int i = 1; i <= n; i++) {
s.push(make_pair(i, num)); //编号 左括号位置
ss += "(";
num++;
while (!s.empty()) {
pair<int, int> temp = s.top();
if (num - temp.second >= l[temp.first] && num - temp.second <= r[temp.first]) {
ss += ")";
s.pop();
num++;
}
else break;
}
}
if (s.empty()) cout << ss << endl;
else puts("IMPOSSIBLE");
return 0;
}