思路:
使用set即可,细节很多,容易出错。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int INF = 0x3f3f3f3f; 4 const int MAXN = 200005; 5 int a[MAXN], l[MAXN], r[MAXN]; 6 int main() 7 { 8 int n, q; 9 while (cin >> n >> q) 10 { 11 for (int i = 1; i <= q; i++) { l[i] = INF; r[i] = -INF; } 12 int c0 = 0, cq = 0; 13 for (int i = 1; i <= n; i++) 14 { 15 cin >> a[i]; 16 c0 += a[i] == 0; 17 cq += a[i] == q; 18 if (a[i] == 0) continue; 19 l[a[i]] = min(l[a[i]], i); 20 r[a[i]] = max(r[a[i]], i); 21 } 22 if (!c0 && !cq) { cout << "NO" << endl; continue; } 23 set<int> st; 24 bool flg = true; 25 for (int i = 1; i <= n; i++) 26 { 27 if (i == l[a[i]]) st.insert(a[i]); 28 if (a[i] && !st.empty() && *st.rbegin() != a[i]) { flg = false; break; } 29 int tmp = -1; 30 if (a[i] == 0) 31 { 32 if (cq == 0) { tmp = q; cq++; } 33 else if (!st.empty()) tmp = *st.rbegin(); 34 else tmp = 1; 35 } 36 if (i == r[a[i]]) st.erase(st.find(a[i])); 37 if (tmp != -1) a[i] = tmp; 38 } 39 if (!cq || !flg) { cout << "NO" << endl; continue; } 40 cout << "YES" << endl; 41 for (int i = 1; i <= n; i++) cout << a[i] << " "; 42 cout << endl; 43 } 44 return 0; 45 }