noip模擬賽 寫代碼
阿新 • • 發佈:2017-11-04
size ges 之間 spa 貪心 技術 不能 問題 namespace
分析:這其實就是括號匹配題,一眼貪心題,不過一開始貪錯了,以為([)]是合法的......其實括號之間不能嵌套.
一開始的想法是盡量往左邊填左括號,因為每種括號的數量都確定了,那麽左括號和右括號的數量也就確定了,但是這樣會有一個問題: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 (inti = 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]); else printf("-%d ", a[i]); } return 0; }
noip模擬賽 寫代碼