1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #pragma GCC optimize ("Ofast") #pragma GCC optimize ("O3") int seg[400000];
class Solution { void update(int u, int s, int e, int l, int r, int v) { if(r < s or e < l) return; if(l <= s and e <= r) { seg[u] = v; return; } int m = (s + e) >> 1; update(u * 2, s, m, l, r, v); update(u * 2 + 1, m + 1, e, l, r, v); seg[u] = seg[u * 2] & seg[u * 2 + 1]; } int query(int u, int s, int e, int l, int r) { if(r < s or e < l) return INT_MAX; if(l <= s and e <= r) return seg[u]; int m = (s + e) >> 1; return query(u * 2, s, m, l, r) & query(u * 2 + 1, m + 1, e, l, r); } int ternarySearch(int l, int r, int n, int t) { int s = l; int res = min(abs(t - query(1,1,n,s,l)), abs(t-query(1,1,n,s,r))); while(l + 3 <= r) { int p = (l * 2 + r) / 3, q = (l + r * 2) / 3; int qq = query(1, 1, n, s, q), qp = query(1, 1, n, s, p);
qp = abs(qp - t); qq = abs(qq - t); res = min({res, qq, qp}); if(qp < qq) l = p; else r = q; } for(int i = l; i <= r; i++) res = min(res, abs(query(1,1,n,s,i) - t)); return res; } public: int closestToTarget(vector<int>& a, int target) { int n = a.size(), l = 1, r = 1, res = INT_MAX; for(int i = 1; i < n; i++) { if(a[i] == a[r-1]) continue; a[r++] = a[i]; } for(int i = 0; i < r; i++) { update(1, 1, r, i + 1, i + 1, a[i]); } for(int i = 1; i <= r; i++) res = min(res, ternarySearch(i,r,r,target)); return res; } };
|