P9446题解
题面
贪心思路
尝试贪心策略:
先按照左括号数量(下文称为
-
nl > nr —— ① 。 -
nl = nr —— ② 。 -
nl < nr —— ③ 。
注意到:要使合成的括号串合法,则
而对于
- 全是左括号。
- 有左有右。
同理,对于
- 全是右括号。
- 有左有右。
显然地,只有一种括号的串应该放在最左或最右边。
现在来讨论
对于
3
)))(((((((
(((
))))))
不难发现,对于
可以发现:按照右括号的数量升序排序是满足该要求的。
综上,只需在原有的排序基础上对
检查/特判
如果存在数据:
3
)(
)(
)(
显然,此时无论怎么排列都不合法。
所以需要特判:
对除了纯左/右以外的所有括号串进行判断:
定义变量
code
最后给出参考代码:
仅作思路参考,切勿模仿。
#include<iostream>
#include<algorithm>
#include<stack>
#include<vector>
using namespace std;
const int maxn = 1e6+5;
struct st {
int l = 0, r = 0, num;
string s;
};
int n;
vector<st> lt;
void check(string s, int len, int j) { // 预处理,先将子串匹配
stack<char> sta;
for(int i = 0; i < len; i++) {
if(s[i] == '(') sta.push(s[i]);
else if(s[i] == ')' && !sta.empty()) sta.pop();
else lt[j].r++; //
}
lt[j].l += sta.size(); // 匹配完了栈内的元素就是 l 的数量
}
bool cmp(st x, st y) {
return x.r < y.r; //
}
int bal = 0;
vector<st> mid, al, ar, ll, rr, spmid;
//l = r = 0的,全是l的,全是r的,l和r都有但l或者r更多的,还有l = r != 0
void init() {
cin >> n;
lt.resize(n);
string a;
for(int i = 0; i < n; i++) {
cin >> a;
lt[i].num = i;
lt[i].s = a;
check(a, a.size(), i);
if(!lt[i].l && !lt[i].r) mid.push_back(lt[i]); // 无多余
else if(lt[i].l && !lt[i].r) al.push_back(lt[i]); // 全是左
else if(!lt[i].l && lt[i].r) ar.push_back(lt[i]); // 全是右
else if(lt[i].l > lt[i].r) ll.push_back(lt[i]); // 左比右多
else if(lt[i].l == lt[i].r && lt[i].l) spmid.push_back(lt[i]); // l=r 特判
else rr.push_back(lt[i]); // 右比左多
}
sort(ll.begin(), ll.end(), cmp);
sort(rr.begin(), rr.end(), cmp);
}
bool spe() { // 特判,防形如“)))(((((((”的情况
for(const auto &e : ll)
for(char c : e.s) {
if(c == '(') bal++;
else bal--;
if(bal < 0) return false;
}
for(const auto &e : spmid)
for(char c : e.s) {
if(c == '(') bal++;
else bal--;
if(bal < 0) return false;
}
for(const auto &e : rr)
for(char c : e.s) {
if(c == '(') bal++;
else bal--;
if(bal < 0) return false;
}
return true;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
init();
if(al.empty() || ar.empty()) {//特判
if(!spe()) {
cout << "impossible" << endl;
return 0;
}
}
bal = 0;//判定是否平衡
for(const auto &e : al) bal += e.l;
for(const auto &e : ll) bal += (e.l - e.r);
for(const auto &e : rr) bal -= (e.r - e.l);
for(const auto &e : ar) bal -= e.r;
if(bal) {
cout << "impossible" << endl;
return 0;
} else {//输出
for(const auto &e : al) cout << e.num + 1 << endl;
for(const auto &e : ll) cout << e.num + 1 << endl;
for(const auto &e : mid) cout << e.num + 1 << endl;
for(const auto &e : spmid) cout << e.num + 1 << endl;
for(const auto &e : rr) cout << e.num + 1 << endl;
for(const auto &e : ar) cout << e.num + 1 << endl;
}
}