Editorial for Dãy Luân Phiên
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 2e5 + 5; int n, a[N]; struct Node { int j, x, y; int p, t; }; vector<Node> dp[N]; int sgn(int x) { if (x > 0) return 1; if (x < 0) return -1; return 0; } bool ok(int last, int dir, int val) { if (last == val) return false; int nd = sgn(val - last); return dir == 0 || nd != dir; } void add(vector<int> &v, int x) { if (x == -1) return; for (int y : v) if (y == x) return; v.push_back(x); } vector<Node> cut(vector<Node> v) { vector<int> keep; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { int mn = -1, mx = -1, emp = -1; for (int i = 0; i < v.size(); i++) { if (v[i].x != x || v[i].y != y) continue; if (v[i].j == 0) emp = i; else { if (mn == -1 || a[v[i].j] < a[v[mn].j]) mn = i; if (mx == -1 || a[v[i].j] > a[v[mx].j]) mx = i; } } if (y == 1) add(keep, mx); else if (y == -1) add(keep, mn); else { add(keep, emp); add(keep, mn); add(keep, mx); } } } vector<Node> res; for (int id : keep) res.push_back(v[id]); return res; } void solve() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= n; i++) dp[i].clear(); dp[1].push_back({0, 0, 0, -1, 0}); for (int i = 1; i < n; i++) { vector<Node> ndp; int val = a[i + 1]; for (int id = 0; id < dp[i].size(); id++) { Node cur = dp[i][id]; if (ok(a[i], cur.x, val)) { ndp.push_back({cur.j, sgn(val - a[i]), cur.y, id, 1}); } if (cur.j == 0) { ndp.push_back({i, 0, cur.x, id, 2}); } else if (ok(a[cur.j], cur.y, val)) { ndp.push_back({i, sgn(val - a[cur.j]), cur.x, id, 2}); } } dp[i + 1] = cut(ndp); if (dp[i + 1].empty()) { cout << "NO\n"; return; } } vector<int> ans(n + 1); int id = 0; int ca = 1, cb = 2; for (int i = n; i >= 2; i--) { Node cur = dp[i][id]; ans[i] = ca; if (cur.t == 2) swap(ca, cb); id = cur.p; } ans[1] = ca; cout << "YES\n"; for (int i = 1; i <= n; i++) cout << ans[i] << ' '; cout << '\n'; } signed main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) solve(); }
Comments