分析:这其实就是括号匹配题,一眼贪心题,不过一开始贪错了,以为([)]是合法的......其实括号之间不能嵌套.
一开始的想法是尽量往左边填左括号,因为每种括号的数量都确定了,那么左括号和右括号的数量也就确定了,但是这样会有一个问题:1 1 1 2 3 1 1 3 2 1,最后两个1被指定为右括号,这样的贪心会使它嵌套.正着贪心似乎很难,沿用之前模拟赛的思路,倒着贪心:从已知推向未知.
题目中告诉了右括号的位置,从后往前枚举,为了尽可能地防止嵌套,在右边如果能放左括号就尽量放左括号,不行就放右括号,最后判断一下能不能合法就可以了.
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm>using namespace std;int n, m, a[1000010], cnt[1000010], pos[1000010],p[1000010], ans[1000010], tot[1000010];int main() {scanf("%d", &n);for (int i = 1; i <= n; i++){scanf("%d", &a[i]);cnt[a[i]]++; }for (int i = 1; i <= n; i++)if (cnt[i] % 2 != 0){printf("NO\n");return 0;}scanf("%d", &m);for (int i = 1; i <= m; i++){int t;scanf("%d", &t);pos[t] = 1;}for (int i = n; i >= 1; i--){if (pos[i] == 1){tot[a[i]]++;ans[i] = 2;p[a[i]]--;}else{if (tot[a[i]] >= 1){tot[a[i]]--;ans[i] = 1;p[a[i]]++;}else{tot[a[i]]++;ans[i] = 2;p[a[i]]--;}}}for (int i = 1; i <= n; i++)if (p[i] != 0){printf("NO\n");return 0;}for (int i = 1; i <= n; i++){if (ans[i] == 1)printf("+%d ", a[i]);elseprintf("-%d ", a[i]);}return 0; }