题面
来源:USACO 官网。模型收到的是同一份题面的文字。
Farmer John's farm is full of lush vegetation and every cow wants a photo of its natural beauty. Unfortunately, Bessie still has places to be, but she doesn't want to disrupt any photo ops.
Bessie is currently standing at $(X,0)$ on the XY-plane and she wants to get to $(0,Y)$ ($1\le X,Y\le 10^6$). Unfortunately, $N$ ($1 \leq N \leq 3 \cdot 10^5$) other cows have decided to pose on the $X$ axis. More specifically, cow $i$ will be positioned at $(x_i,0)$ with a photographer at $(0,y_i)$ where $(1 \leq x_i,y_i \leq 10^6)$ ready to take their picture. They will begin posing moments before time $s_i$ ($1 \leq s_i < T$) and they will keep posing for a very long time (they have to get their picture just right). Here, $1\le T\le N+1$.
Bessie knows the schedule for every cow's photo op, and she will take the shortest Euclidean distance to get to her destination, without crossing the line of sight from any photographer to their respective cow (her path will consist of one or more line segments).
If Bessie leaves at time $t$, she will avoid the line of sights for all photographer/cow pairs that started posing at time $s_i \le t$, and let the distance to her final destination be $d_t$. Determine the values of $\lfloor d_t\rfloor$ for each integer $t$ from $0$ to $T-1$ inclusive.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line of input contains $N$ and $T$, representing the number of cows posing on the $x$-axis and the timeframe that Bessie could leave at.The second line of input contains $X$ and $Y$, representing Bessie's starting $X$ coordinate and her target $Y$ coordinate respectively.
The next $N$ lines contain $s_i$ $x_i$ and $y_i$. It is guaranteed that all $x_i$ are distinct from each other and $X$, and all $y_i$ are distinct from each other and $Y$. All $s_i$ will be given in increasing order, where $s_i \leq s_{i+1}$.
OUTPUT FORMAT (print output to the terminal / stdout):
Print $T$ lines, with the $t$th (0-indexed) line containing $\lfloor d_t\rfloor$.SAMPLE INPUT:
4 5 6 7 1 7 5 2 4 4 3 1 6 4 2 9
SAMPLE OUTPUT:
9 9 9 10 12
SAMPLE INPUT:
2 3 10 7 1 2 10 1 9 1
SAMPLE OUTPUT:
12 16 16
For $t=0$ the answer is $\lfloor \sqrt{149} \rfloor=12$.
For $t=1$ the answer is $\lfloor 14+\sqrt 5\rfloor=16$.
SAMPLE INPUT:
5 6 8 9 1 3 5 1 4 1 3 10 7 4 9 2 5 6 6
SAMPLE OUTPUT:
12 12 12 12 14 14
For $t=5$ the answer is $\lfloor 1+\sqrt{9^2+7^2}+2\rfloor=14$. Path: $(8,0)\to (9,0)\to (0,7)\to (0,9)$
SCORING:
- Inputs 4-6: $N\le 100$
- Inputs 7-9: $N\le 3000$
- Inputs 10-12: $T\le 10$
- Inputs 13-18: No additional constraints
Problem credits: Suhas Nagar
结果
Kimi K3.1 ProKimi
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 58.0k平均输出 token(含思考) ↓
- 24.5输出速度 tokens/s ↑
- 2218 秒延迟 ↓
- 1.09×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
DeepSeek Flash V4.1-1017DeepSeek
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 92.9k平均输出 token(含思考) ↓
- 200.3输出速度 tokens/s ↑
- 414 秒延迟 ↓
- 1.04×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
MiniMax M3.1 FlashMiniMax
1/3
解出的采样 ↑
- 100采样 1 · 解出
- 0.0采样 2 · 编译错误
- 33.3采样 3 · 答案错误
- 88.6k平均输出 token(含思考) ↓
- 146.9输出速度 tokens/s ↑
- 577 秒延迟 ↓
- 1.69×CPU 时间 / 官方解 ↓
- 同阶 1时间复杂度(相对官方解)
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
#include <bits/stdc++.h> using namespace std; using ll = long long; using i128 = __int128_t; const int INF = 1000000000; struct Cost { ll K, S; // K + sqrt(S) }; bool costLess(const Cost& A, const Cost& B) { ll c = B.K - A.K; if (c == 0) return A.S < B.S; if (c > 0) { if (A.S <= B.S) return true; i128 C = c; i128 D = (i128)A.S - B.S - C * C; if (D < 0) return true; return D * D < (i128)4 * C * C * B.S; } else { i128 D0 = -(i128)c; i128 D = (i128)B.S - A.S - D0 * D0; if (D <= 0) return false; return (i128)4 * D0 * D0 * A.S < D * D; } } struct Entry { Cost c; int j, b; }; struct EntryCmp { bool operator()(const Entry& a, const Entry& b) const { if (costLess(b.c, a.c)) return true; if (costLess(a.c, b.c)) return false; if (a.j != b.j) return a.j > b.j; return a.b > b.b; } }; struct ActiveSegTree { int n; vector<int> mn, mx; ActiveSegTree(int n_) : n(n_), mn(4 * n_ + 5, INF), mx(4 * n_ + 5, 0) {} void update(int node, int l, int r, int p, int v) { if (l == r) { mn[node] = mx[node] = v; return; } int m = (l + r) >> 1; if (p <= m) update(node << 1, l, m, p, v); else update(node << 1 | 1, m + 1, r, p, v); mn[node] = min(mn[node << 1], mn[node << 1 | 1]); mx[node] = max(mx[node << 1], mx[node << 1 | 1]); } void update(int p, int v) { update(1, 1, n, p, v); } int firstGreater(int node, int l, int r, int ql, int qr, int v) { if (r < ql || l > qr || mx[node] <= v) return n + 1; if (l == r) return l; int m = (l + r) >> 1; int res = firstGreater(node << 1, l, m, ql, qr, v); if (res != n + 1) return res; return firstGreater(node << 1 | 1, m + 1, r, ql, qr, v); } int firstGreater(int ql, int qr, int v) { if (ql > qr) return n + 1; return firstGreater(1, 1, n, ql, qr, v); } int lastLess(int node, int l, int r, int ql, int qr, int v) { if (r < ql || l > qr || mn[node] >= v) return 0; if (l == r) return l; int m = (l + r) >> 1; int res = lastLess(node << 1 | 1, m + 1, r, ql, qr, v); if (res != 0) return res; return lastLess(node << 1, l, m, ql, qr, v); } int lastLess(int ql, int qr, int v) { if (ql > qr) return 0; return lastLess(1, 1, n, ql, qr, v); } }; struct RunMap { struct Info { int s, e, v; }; int n; map<int, int> mp; RunMap(int n_, int initial) : n(n_) { mp[0] = initial; } map<int, int>::iterator split(int p) { if (p == 0) return mp.begin(); auto it = mp.lower_bound(p); if (it != mp.end() && it->first == p) return it; auto prv = prev(it); return mp.emplace(p, prv->second).first; } void assignRange(int l, int r, int v) { split(l); if (r < n) split(r + 1); auto it = mp.lower_bound(l); auto jt = (r < n ? mp.lower_bound(r + 1) : mp.end()); mp.erase(it, jt); mp[l] = v; } int get(int p) const { return prev(mp.upper_bound(p))->second; } Info info(int p) const { auto it = prev(mp.upper_bound(p)); auto nx = next(it); return {it->first, nx == mp.end() ? n : nx->first - 1, it->second}; } }; struct ValidSet { int n; vector<int> nx, pr; vector<char> alive; ValidSet(int n_) : n(n_), nx(n_ + 2), pr(n_ + 1), alive(n_ + 1, 1) { iota(nx.begin(), nx.end(), 0); iota(pr.begin(), pr.end(), 0); } int findNext(int x) { if (x > n) return n + 1; return nx[x] == x ? x : nx[x] = findNext(nx[x]); } int findPrev(int x) { if (x < 0) return -1; return pr[x] == x ? x : pr[x] = findPrev(pr[x]); } int successor(int x) { return findNext(x); } int predecessor(int x) { return findPrev(x); } void eraseRange(int l, int r) { l = max(l, 0); r = min(r, n); if (l > r) return; int j = findNext(l); while (j <= r) { alive[j] = 0; int nj = findNext(j + 1); nx[j] = nj; pr[j] = findPrev(j - 1); j = nj; } } }; struct Cow { int s, x, y, idx; }; struct Solver { int n, X, Y, kx; vector<ll> a, axisCost; ActiveSegTree active; RunMap L, R; ValidSet valid; priority_queue<Entry, vector<Entry>, EntryCmp> lowPQ, highPQ; int firstHigh, lastLow; Solver(int n_, int X_, int Y_, const vector<int>& xs) : n(n_), X(X_), Y(Y_), a(n_ + 1), axisCost(n_ + 1), active(n_), L(n_, 0), R(n_, INF), valid(n_), firstHigh(n_ + 1), lastLow(0) { kx = 0; for (int i = 1; i <= n; i++) { if (xs[i] < X) kx++; } for (int j = 0; j <= n; j++) { if (j < kx) a[j] = xs[j + 1]; else if (j == kx) a[j] = X; else a[j] = xs[j]; axisCost[j] = llabs((ll)X - a[j]); } } Cost makeCost(int j, int b) const { return { axisCost[j] + llabs((ll)Y - b), a[j] * a[j] + (ll)b * b }; } void addLowCandidate(int g) { if (g < 0 || g > n) return; auto run = R.info(g); if (run.v >= Y) return; int st = max(run.s, kx + 1); if (st > run.e || !valid.alive[st]) return; lowPQ.push({makeCost(st, run.v), st, run.v}); } void addHighCandidate(int g) { if (g < 0 || g > n) return; auto run = L.info(g); if (run.v <= Y) return; int en = min(run.e, kx - 1); if (en < run.s || en < 0 || !valid.alive[en]) return; highPQ.push({makeCost(en, run.v), en, run.v}); } void activate(int k, int y) { if (k > 1) { int i = active.firstGreater(1, k - 1, y); if (i <= k - 1) valid.eraseRange(i, k - 1); } if (k < n) { int i = active.lastLess(k + 1, n, y); if (i >= k + 1) valid.eraseRange(k, i - 1); } if (y > Y) firstHigh = min(firstHigh, k); else lastLow = max(lastLow, k); bool changedL = false, changedR = false; int leftR = 0, rightR = 0; auto it = prev(L.mp.upper_bound(k)); if (it->second < y) { auto jt = it; while (jt != L.mp.end() && jt->second < y) ++jt; int r = (jt == L.mp.end() ? n : jt->first - 1); L.assignRange(k, r, y); changedL = true; } int r = k - 1; if (r >= 0) { it = prev(R.mp.upper_bound(r)); if (it->second > y) { auto first = it; while (first != R.mp.begin()) { auto prv = prev(first); if (prv->second <= y) break; first = prv; } leftR = first->first; rightR = r; R.assignRange(leftR, rightR, y); changedR = true; } } active.update(k, y); if (changedL) { addHighCandidate(k - 1); addHighCandidate(k); } if (changedR) { addLowCandidate(leftR); addLowCandidate(rightR + 1); } } static ll floorSqrt(ll s) { ll r = sqrtl((long double)s); while ((i128)(r + 1) * (r + 1) <= s) r++; while ((i128)r * r > s) r--; return r; } ll answer() { Cost best{(ll)X + Y, 0}; bool have = true; auto take = [&](const Cost& c) { if (!have || costLess(c, best)) { best = c; have = true; } }; if (lastLow < firstHigh) { int l = lastLow; int r = firstHigh - 1; int j = min(max(kx, l), r); take(makeCost(j, Y)); } if (lastLow > 0) { int lim = min(kx, lastLow - 1); if (lim >= 0) { int j = valid.predecessor(lim); if (j >= 0) take(makeCost(j, R.get(j))); } } if (firstHigh <= n) { int lim = max(kx, firstHigh); int j = valid.successor(lim); if (j <= n) take(makeCost(j, L.get(j))); } while (!lowPQ.empty()) { const Entry& e = lowPQ.top(); bool ok = e.j > kx && valid.alive[e.j] && R.get(e.j) == e.b; if (!ok) lowPQ.pop(); else break; } if (!lowPQ.empty()) take(lowPQ.top().c); while (!highPQ.empty()) { const Entry& e = highPQ.top(); bool ok = e.j < kx && valid.alive[e.j] && L.get(e.j) == e.b; if (!ok) highPQ.pop(); else break; } if (!highPQ.empty()) take(highPQ.top().c); return best.K + floorSqrt(best.S); } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, T; cin >> N >> T; int X, Y; cin >> X >> Y; vector<Cow> cows(N); for (int i = 0; i < N; i++) { cin >> cows[i].s >> cows[i].x >> cows[i].y; } vector<int> order(N); iota(order.begin(), order.end(), 0); sort(order.begin(), order.end(), [&](int i, int j) { return cows[i].x < cows[j].x; }); vector<int> xs(N + 1); for (int i = 0; i < N; i++) { int id = order[i]; xs[i + 1] = cows[id].x; cows[id].idx = i + 1; } Solver solver(N, X, Y, xs); int ptr = 0; for (int t = 0; t < T; t++) { while (ptr < N && cows[ptr].s <= t) { solver.activate(cows[ptr].idx, cows[ptr].y); ptr++; } cout << solver.answer() << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; struct Comp { int mnx, mxx, mny, mxy; }; struct Cow { int s, x, y; }; static ll floorSqrt(ll n) { ll r = (ll)sqrt((double)n); while ((r + 1) * (r + 1) <= n) ++r; while (r * r > n) --r; return r; } class Solver { public: int X, Y; map<int, Comp*> comps; // Ordered by minimum x, key = mnx. multiset<ll> gapValues; Solver(int X_, int Y_) : X(X_), Y(Y_) { gapValues.insert(gapCost(nullptr, nullptr)); } // The valid rectangle between two consecutive components is // [left.maxX, right.minX] x [left.maxY, right.minY]. // A null left/right denotes the unbounded initial/final side. ll gapCost(const Comp* left, const Comp* right) const { ll a = X, b = Y; if (left) { a = max(a, (ll)left->mxx); b = max(b, (ll)left->mxy); } if (right) { a = min(a, (ll)right->mnx); b = min(b, (ll)right->mny); } ll axisDistance = llabs(a - X) + llabs(b - Y); return axisDistance + floorSqrt(a * a + b * b); } void removeGap(const Comp* left, const Comp* right) { ll value = gapCost(left, right); auto it = gapValues.find(value); gapValues.erase(it); } void addGap(const Comp* left, const Comp* right) { gapValues.insert(gapCost(left, right)); } void addPoint(int x, int y) { auto right = comps.lower_bound(x); bool inside = false; map<int, Comp*>::iterator center; if (right != comps.begin()) { auto previous = prev(right); if (previous->second->mxx > x) { inside = true; center = previous; } } // Existing components that will merge with the new segment: // the half-open range [first, last). map<int, Comp*>::iterator first, last; if (inside) { first = center; while (first != comps.begin()) { auto previous = prev(first); if (previous->second->mxy > y) first = previous; else break; } last = next(center); while (last != comps.end() && last->second->mny < y) { ++last; } } else { first = right; while (first != comps.begin()) { auto previous = prev(first); if (previous->second->mxy > y) first = previous; else break; } last = right; while (last != comps.end() && last->second->mny < y) { ++last; } } Comp* leftOutside = nullptr; if (first != comps.begin()) { leftOutside = prev(first)->second; } Comp* rightOutside = nullptr; if (last != comps.end()) { rightOutside = last->second; } if (first == last) { // A new singleton component splits one existing gap. removeGap(leftOutside, rightOutside); } else { // Remove every gap incident to the merged range. removeGap(leftOutside, first->second); for (auto it = first; it != last; ++it) { auto nx = next(it); Comp* nextComp = (nx == comps.end() ? nullptr : nx->second); removeGap(it->second, nextComp); } } Comp* merged = new Comp{x, x, y, y}; for (auto it = first; it != last; ++it) { Comp* c = it->second; merged->mnx = min(merged->mnx, c->mnx); merged->mxx = max(merged->mxx, c->mxx); merged->mny = min(merged->mny, c->mny); merged->mxy = max(merged->mxy, c->mxy); } if (first != last) { comps.erase(first, last); } auto inserted = comps.emplace(merged->mnx, merged).first; Comp* newLeft = nullptr; if (inserted != comps.begin()) { newLeft = prev(inserted)->second; } Comp* newRight = nullptr; auto after = next(inserted); if (after != comps.end()) { newRight = after->second; } addGap(newLeft, merged); addGap(merged, newRight); } ll answer() const { return *gapValues.begin(); } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, T; cin >> N >> T; int X, Y; cin >> X >> Y; vector<Cow> cows(N); for (Cow& cow : cows) { cin >> cow.s >> cow.x >> cow.y; } Solver solver(X, Y); int index = 0; for (int t = 0; t < T; ++t) { while (index < N && cows[index].s <= t) { solver.addPoint(cows[index].x, cows[index].y); ++index; } cout << solver.answer() << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; const int INF = 1000000000; int SX, SY; mt19937 rng(712367821); struct Rect { int xl, xr, yl, yr; int val; }; int integerSqrt(ll x) { ll r = sqrt((long double)x); while ((r + 1) * (r + 1) <= x) ++r; while (r * r > x) --r; return (int)r; } int evaluate(const Rect &re) { ll a, b; if (SX < re.xl) a = re.xl; else if (SX > re.xr) a = re.xr; else a = SX; if (SY < re.yl) b = re.yl; else if (SY > re.yr) b = re.yr; else b = SY; ll base = llabs((ll)SX - a) + llabs((ll)SY - b); ll sq = a * a + b * b; return (int)(base + integerSqrt(sq)); } Rect makeRect(int xl, int xr, int yl, int yr) { Rect re{xl, xr, yl, yr, 0}; re.val = evaluate(re); return re; } struct Node { Rect re; Node *L, *R; int sz; unsigned pri; int mxl, mxr, myl, myr; Node(const Rect &r) : re(r), L(nullptr), R(nullptr), sz(1), pri(rng()) { mxl = re.xl; mxr = re.xr; myl = re.yl; myr = re.yr; } }; int getSize(Node *t) { return t ? t->sz : 0; } void pull(Node *t) { if (!t) return; t->sz = 1 + getSize(t->L) + getSize(t->R); t->mxl = t->re.xl; t->mxr = t->re.xr; t->myl = t->re.yl; t->myr = t->re.yr; if (t->L) { t->mxl = max(t->mxl, t->L->mxl); t->mxr = max(t->mxr, t->L->mxr); t->myl = max(t->myl, t->L->myl); t->myr = max(t->myr, t->L->myr); } if (t->R) { t->mxl = max(t->mxl, t->R->mxl); t->mxr = max(t->mxr, t->R->mxr); t->myl = max(t->myl, t->R->myl); t->myr = max(t->myr, t->R->myr); } } Node* mergeTrees(Node *a, Node *b) { if (!a) return b; if (!b) return a; if (a->pri > b->pri) { a->R = mergeTrees(a->R, b); pull(a); return a; } else { b->L = mergeTrees(a, b->L); pull(b); return b; } } // The first k nodes go to a, the remainder to b. void splitTree(Node *t, int k, Node *&a, Node *&b) { if (!t) { a = b = nullptr; return; } int leftSize = getSize(t->L); if (leftSize >= k) { splitTree(t->L, k, a, t->L); b = t; pull(b); } else { splitTree(t->R, k - leftSize - 1, t->R, b); a = t; pull(a); } } int firstXRGreater(Node *t, int x) { if (!t || t->mxr <= x) return -1; int ls = getSize(t->L); if (t->L && t->L->mxr > x) { int res = firstXRGreater(t->L, x); if (res != -1) return res; } if (t->re.xr > x) return ls; if (t->R) { int res = firstXRGreater(t->R, x); if (res != -1) return ls + 1 + res; } return -1; } int firstYRGreater(Node *t, int y) { if (!t || t->myr <= y) return -1; int ls = getSize(t->L); if (t->L && t->L->myr > y) { int res = firstYRGreater(t->L, y); if (res != -1) return res; } if (t->re.yr > y) return ls; if (t->R) { int res = firstYRGreater(t->R, y); if (res != -1) return ls + 1 + res; } return -1; } int firstXLAtLeast(Node *t, int x) { if (!t || t->mxl < x) return -1; int ls = getSize(t->L); if (t->L && t->L->mxl >= x) { int res = firstXLAtLeast(t->L, x); if (res != -1) return res; } if (t->re.xl >= x) return ls; if (t->R) { int res = firstXLAtLeast(t->R, x); if (res != -1) return ls + 1 + res; } return -1; } int firstYLAtLeast(Node *t, int y) { if (!t || t->myl < y) return -1; int ls = getSize(t->L); if (t->L && t->L->myl >= y) { int res = firstYLAtLeast(t->L, y); if (res != -1) return res; } if (t->re.yl >= y) return ls; if (t->R) { int res = firstYLAtLeast(t->R, y); if (res != -1) return ls + 1 + res; } return -1; } multiset<int> answers; Node *root = nullptr; void collectRange(Node *t, int x, int y, vector<Rect> &survivors) { if (!t) return; collectRange(t->L, x, y, survivors); auto it = answers.find(t->re.val); if (it != answers.end()) answers.erase(it); const Rect &re = t->re; // Portion southwest of (x,y). if (re.xl <= x && re.yl <= y) { Rect sw = re; sw.xr = min(re.xr, x); sw.yr = min(re.yr, y); sw.val = evaluate(sw); survivors.push_back(sw); } // Portion northeast of (x,y). if (re.xr >= x && re.yr >= y) { Rect ne = re; ne.xl = max(re.xl, x); ne.yl = max(re.yl, y); ne.val = evaluate(ne); survivors.push_back(ne); } collectRange(t->R, x, y, survivors); delete t; } void addObstacle(int x, int y) { int n = getSize(root); int a = firstXRGreater(root, x); int b = firstYRGreater(root, y); if (a == -1) a = n; if (b == -1) b = n; int left = min(a, b); int c = firstXLAtLeast(root, x); int d = firstYLAtLeast(root, y); if (c == -1) c = n; if (d == -1) d = n; int right = max(c, d); if (left >= right) return; Node *A, *BC, *B, *C; splitTree(root, left, A, BC); splitTree(BC, right - left, B, C); vector<Rect> survivors; survivors.reserve(2); collectRange(B, x, y, survivors); Node *middle = nullptr; for (const Rect &re : survivors) { answers.insert(re.val); middle = mergeTrees(middle, new Node(re)); } root = mergeTrees(A, mergeTrees(middle, C)); } struct Cow { int s, x, y; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, T; cin >> N >> T; cin >> SX >> SY; vector<Cow> cows(N); for (Cow &cow : cows) { cin >> cow.s >> cow.x >> cow.y; } Rect initial = makeRect(0, INF, 0, INF); root = new Node(initial); answers.insert(initial.val); int ptr = 0; for (int t = 0; t < T; ++t) { while (ptr < N && cows[ptr].s <= t) { addObstacle(cows[ptr].x, cows[ptr].y); ++ptr; } cout << *answers.begin() << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; const int MAXN = 300005; const long double INF = 1e30L; struct BlockInfo { int firstX, lastX; int minY, maxY; }; int N, T; int X, Y; vector<int> sarr, xs, ys; int xToIdx[1000005]; int parent[MAXN]; BlockInfo info[MAXN]; struct BlockCmp { bool operator()(int a, int b) const { if (a == b) return false; return info[a].firstX < info[b].firstX; } }; set<int, BlockCmp> blocks; multiset<long double> cuts; set<int> activeX; int findRoot(int v) { if (parent[v] == v) return v; return parent[v] = findRoot(parent[v]); } long double computeCut(int a, int b) { long double Lx = 0, Rx = INF; long double Ly = 0, Ry = INF; if (a != -1) { Lx = info[a].lastX; Ly = info[a].maxY; } if (b != -1) { Rx = info[b].firstX; Ry = info[b].minY; } long double x0 = X; if (x0 < Lx) x0 = Lx; if (x0 > Rx) x0 = Rx; long double y0 = Y; if (y0 < Ly) y0 = Ly; if (y0 > Ry) y0 = Ry; return fabsl(X - x0) + sqrtl(x0 * x0 + y0 * y0) + fabsl(Y - y0); } void addCut(int a, int b) { cuts.insert(computeCut(a, b)); } void removeCut(int a, int b) { long double val = computeCut(a, b); auto it = cuts.find(val); if (it != cuts.end()) cuts.erase(it); } void processMerge(int Lroot, int Rroot, int idx, int xp, int yp) { auto itL = blocks.find(Lroot); auto itR = blocks.find(Rroot); int prevRoot = -1; if (itL != blocks.begin()) { prevRoot = *prev(itL); } auto itAfterR = next(itR); int nextRoot = -1; if (itAfterR != blocks.end()) { nextRoot = *itAfterR; } int firstX = info[Lroot].firstX; int lastX = info[Lroot].lastX; int minY = info[Lroot].minY; int maxY = info[Lroot].maxY; firstX = min(firstX, xp); lastX = max(lastX, xp); minY = min(minY, yp); maxY = max(maxY, yp); auto it = itL; while (true) { int b = *it; firstX = min(firstX, info[b].firstX); lastX = max(lastX, info[b].lastX); minY = min(minY, info[b].minY); maxY = max(maxY, info[b].maxY); if (it == itR) break; ++it; } removeCut(prevRoot, *itL); auto itCur = itL; while (itCur != itR) { auto itNext = next(itCur); removeCut(*itCur, *itNext); itCur = itNext; } removeCut(*itR, nextRoot); int newRoot = Lroot; itCur = itL; while (true) { int b = *itCur; if (b != newRoot) { parent[b] = newRoot; } if (itCur == itR) break; ++itCur; } parent[idx] = newRoot; parent[newRoot] = newRoot; itCur = itL; while (true) { auto toErase = itCur; if (itCur == itR) { blocks.erase(toErase); break; } ++itCur; blocks.erase(toErase); } info[newRoot] = {firstX, lastX, minY, maxY}; blocks.insert(newRoot); addCut(prevRoot, newRoot); addCut(newRoot, nextRoot); } void insertPoint(int idx) { int xp = xs[idx]; int yp = ys[idx]; auto itAct = activeX.lower_bound(xp); int predX = -1, succX = -1; if (itAct != activeX.begin()) { auto itp = prev(itAct); predX = *itp; } if (itAct != activeX.end()) { succX = *itAct; } int rootPred = -1, rootSucc = -1; if (predX != -1) rootPred = findRoot(xToIdx[predX]); if (succX != -1) rootSucc = findRoot(xToIdx[succX]); if (rootPred != -1 && rootSucc != -1 && rootPred == rootSucc) { int B = rootPred; if (yp >= info[B].minY && yp <= info[B].maxY) { parent[idx] = B; activeX.insert(xp); return; } int Lroot = B, Rroot = B; if (yp < info[B].minY) { auto itB = blocks.find(B); auto itCur = itB; while (itCur != blocks.begin()) { auto itPrev = prev(itCur); int pb = *itPrev; if (info[pb].maxY > yp) { Lroot = pb; itCur = itPrev; } else { break; } } } else { auto itB = blocks.find(B); auto itCur = itB; while (true) { auto itNext = next(itCur); if (itNext == blocks.end()) break; int nb = *itNext; if (info[nb].minY < yp) { Rroot = nb; itCur = itNext; } else { break; } } } processMerge(Lroot, Rroot, idx, xp, yp); activeX.insert(xp); return; } int leftBlock = rootPred; int rightBlock = rootSucc; int Lroot = -1, Rroot = -1; bool mergeLeft = false, mergeRight = false; if (leftBlock != -1 && info[leftBlock].maxY > yp) { Lroot = Rroot = leftBlock; auto itLeft = blocks.find(leftBlock); auto itCur = itLeft; while (itCur != blocks.begin()) { auto itPrev = prev(itCur); int b = *itPrev; if (info[b].maxY > yp) { Lroot = b; itCur = itPrev; } else { break; } } mergeLeft = true; } else if (rightBlock != -1 && info[rightBlock].minY < yp) { Lroot = Rroot = rightBlock; auto itRight = blocks.find(rightBlock); auto itCur = itRight; while (true) { auto itNext = next(itCur); if (itNext == blocks.end()) break; int b = *itNext; if (info[b].minY < yp) { Rroot = b; itCur = itNext; } else { break; } } mergeRight = true; } if (!mergeLeft && !mergeRight) { int prevRoot = leftBlock; int nextRoot = rightBlock; removeCut(prevRoot, nextRoot); int newRoot = idx; parent[idx] = idx; info[newRoot] = {xp, xp, yp, yp}; blocks.insert(newRoot); addCut(prevRoot, newRoot); addCut(newRoot, nextRoot); activeX.insert(xp); return; } processMerge(Lroot, Rroot, idx, xp, yp); activeX.insert(xp); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> N >> T; cin >> X >> Y; sarr.resize(N); xs.resize(N); ys.resize(N); memset(xToIdx, -1, sizeof(xToIdx)); for (int i = 0; i < N; i++) { cin >> sarr[i] >> xs[i] >> ys[i]; xToIdx[xs[i]] = i; } for (int i = 0; i < N; i++) { parent[i] = i; } cuts.insert(computeCut(-1, -1)); int ptr = 0; for (int t = 0; t < T; t++) { while (ptr < N && sarr[ptr] <= t) { insertPoint(ptr); ptr++; } long double ans = *cuts.begin(); long long out = (long long)floorl(ans + 1e-12L); cout << out << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; struct Component { int min_x, max_x; int min_y, max_y; }; int X, Y; const long double INF = 1e18L; map<int, Component> comps; multiset<long double> gaps; long double calcGap(const Component* a, const Component* b) { long double A = a ? (long double)a->max_x : 0.0L; long double C = a ? (long double)a->max_y : 0.0L; long double B = b ? (long double)b->min_x : INF; long double D = b ? (long double)b->min_y : INF; long double aa = (long double)X; if (aa < A) aa = A; else if (aa > B) aa = B; long double bb = (long double)Y; if (bb < C) bb = C; else if (bb > D) bb = D; return fabsl((long double)X - aa) + sqrtl(aa * aa + bb * bb) + fabsl((long double)Y - bb); } void addGap(const Component* a, const Component* b) { gaps.insert(calcGap(a, b)); } void removeGap(const Component* a, const Component* b) { long double val = calcGap(a, b); auto it = gaps.find(val); if (it != gaps.end()) gaps.erase(it); } void insertPoint(int x, int y) { auto it = comps.lower_bound(x); vector<map<int, Component>::iterator> merged; bool hasContaining = false; auto containing = comps.end(); if (it != comps.begin()) { auto p = prev(it); if (p->second.max_x > x) { hasContaining = true; containing = p; } } if (hasContaining) { merged.push_back(containing); auto cur = containing; while (cur != comps.begin()) { auto p = prev(cur); if (p->second.max_y > y) { merged.push_back(p); cur = p; } else { break; } } cur = next(containing); while (cur != comps.end() && cur->second.min_y < y) { merged.push_back(cur); ++cur; } } else { auto cur = it; while (cur != comps.begin()) { auto p = prev(cur); if (p->second.max_y > y) { merged.push_back(p); cur = p; } else { break; } } cur = it; while (cur != comps.end() && cur->second.min_y < y) { merged.push_back(cur); ++cur; } } if (merged.empty()) { Component* prevComp = nullptr; Component* nextComp = nullptr; if (it != comps.begin()) prevComp = &(prev(it)->second); if (it != comps.end()) nextComp = &(it->second); removeGap(prevComp, nextComp); Component c{x, x, y, y}; auto inserted = comps.emplace(x, c).first; addGap(prevComp, &(inserted->second)); addGap(&(inserted->second), nextComp); return; } auto l = merged[0]; auto r = merged[0]; for (auto v : merged) { if (v->first < l->first) l = v; if (v->first > r->first) r = v; } auto nextIt = next(r); Component* prevComp = (l == comps.begin() ? nullptr : &(prev(l)->second)); Component* nextComp = (nextIt == comps.end() ? nullptr : &(nextIt->second)); removeGap(prevComp, &(l->second)); for (auto cur = l; ; ++cur) { auto nxt = next(cur); Component* nxtComp = (nxt == comps.end() ? nullptr : &(nxt->second)); removeGap(&(cur->second), nxtComp); if (cur == r) break; } int minx = min(x, l->second.min_x); int maxx = max(x, r->second.max_x); int miny = min(y, l->second.min_y); int maxy = max(y, r->second.max_y); comps.erase(l, next(r)); Component c{minx, maxx, miny, maxy}; auto inserted = comps.emplace(minx, c).first; addGap(prevComp, &(inserted->second)); addGap(&(inserted->second), nextComp); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, T; cin >> N >> T; cin >> X >> Y; vector<int> s(N), xs(N), ys(N); for (int i = 0; i < N; ++i) { cin >> s[i] >> xs[i] >> ys[i]; } gaps.insert(calcGap(nullptr, nullptr)); int idx = 0; for (int t = 0; t < T; ++t) { while (idx < N && s[idx] <= t) { insertPoint(xs[idx], ys[idx]); ++idx; } long double best = *gaps.begin(); long double axisPath = (long double)X + (long double)Y; if (axisPath < best) best = axisPath; long long answer = (long long)floorl(best + 1e-12L); cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; struct Block { ll Lx, Rx; ll Ly, Ry; }; map<ll, Block> blocks; // keyed by Lx multiset<ld> gapCosts; ll X, Y; ld getCost(Block* A, Block* B) { ll a_low, a_high, b_low, b_high; const ll INF = (ll)4e18; if (A == nullptr) { a_low = 0; a_high = (B == nullptr ? INF : B->Lx); } else { a_low = A->Rx; a_high = (B == nullptr ? INF : B->Lx); } if (A == nullptr) { b_low = 0; b_high = (B == nullptr ? INF : B->Ly); } else { b_low = A->Ry; b_high = (B == nullptr ? INF : B->Ly); } ll a; if (X < a_low) a = a_low; else if (X > a_high) a = a_high; else a = X; ll b; if (Y < b_low) b = b_low; else if (Y > b_high) b = b_high; else b = Y; ld dx = fabsl((ld)X - a); ld dy = fabsl((ld)Y - b); ld hyp = sqrtl((ld)a * a + (ld)b * b); return dx + dy + hyp; } void addGap(Block* A, Block* B) { if (A == nullptr && B == nullptr) return; gapCosts.insert(getCost(A, B)); } void removeGap(Block* A, Block* B) { if (A == nullptr && B == nullptr) return; ld c = getCost(A, B); auto it = gapCosts.find(c); if (it != gapCosts.end()) gapCosts.erase(it); } map<ll, Block>::iterator mergeBlocks(map<ll, Block>::iterator itA, map<ll, Block>::iterator itB) { Block A = itA->second; Block B = itB->second; bool hasPrev = (itA != blocks.begin()); auto itPrev = hasPrev ? prev(itA) : blocks.end(); auto itNext = next(itB); bool hasNext = (itNext != blocks.end()); if (hasPrev) removeGap(&itPrev->second, &A); else removeGap(nullptr, &A); removeGap(&A, &B); if (hasNext) removeGap(&B, &itNext->second); else removeGap(&B, nullptr); Block M; M.Lx = A.Lx; M.Rx = B.Rx; M.Ly = min(A.Ly, B.Ly); M.Ry = max(A.Ry, B.Ry); blocks.erase(itB); itA->second = M; if (hasPrev) addGap(&itPrev->second, &itA->second); else addGap(nullptr, &itA->second); if (hasNext) addGap(&itA->second, &itNext->second); else addGap(&itA->second, nullptr); return itA; } map<ll, Block>::iterator normalize(map<ll, Block>::iterator it) { bool changed = true; while (changed) { changed = false; if (it != blocks.begin()) { auto lit = prev(it); if (lit->second.Ry > it->second.Ly) { it = mergeBlocks(lit, it); changed = true; continue; } } auto rit = next(it); if (rit != blocks.end()) { if (it->second.Ry > rit->second.Ly) { it = mergeBlocks(it, rit); changed = true; continue; } } } return it; } void addPoint(ll x, ll y) { auto it = blocks.upper_bound(x); if (it != blocks.begin()) { auto prevIt = prev(it); if (prevIt->second.Lx <= x && x <= prevIt->second.Rx) { // inside existing block Block& cur = prevIt->second; auto nextIt = next(prevIt); auto beforeIt = (prevIt == blocks.begin() ? blocks.end() : prev(prevIt)); if (prevIt == blocks.begin()) removeGap(nullptr, &cur); else removeGap(&beforeIt->second, &cur); if (nextIt == blocks.end()) removeGap(&cur, nullptr); else removeGap(&cur, &nextIt->second); cur.Ly = min(cur.Ly, y); cur.Ry = max(cur.Ry, y); if (prevIt == blocks.begin()) addGap(nullptr, &cur); else addGap(&beforeIt->second, &cur); if (nextIt == blocks.end()) addGap(&cur, nullptr); else addGap(&cur, &nextIt->second); normalize(prevIt); return; } } // in a gap auto rightIt = blocks.lower_bound(x); auto leftIt = (rightIt == blocks.begin() ? blocks.end() : prev(rightIt)); Block* left = (leftIt == blocks.end() ? nullptr : &leftIt->second); Block* right = (rightIt == blocks.end() ? nullptr : &rightIt->second); removeGap(left, right); Block nb{x, x, y, y}; auto newIt = blocks.emplace(x, nb).first; addGap(left, &newIt->second); addGap(&newIt->second, right); normalize(newIt); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, T; cin >> N >> T; cin >> X >> Y; vector<int> s(N); vector<ll> x(N), y(N); for (int i = 0; i < N; ++i) { cin >> s[i] >> x[i] >> y[i]; } int idx = 0; for (int t = 0; t < T; ++t) { while (idx < N && s[idx] <= t) { addPoint(x[idx], y[idx]); ++idx; } ll ans; if (blocks.empty()) { ld d = sqrtl((ld)X * X + (ld)Y * Y); ans = (ll)floorl(d + 1e-12L); } else { ld best = *gapCosts.begin(); ans = (ll)floorl(best + 1e-12L); } cout << ans << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; static constexpr double INF_COST = 1e100; static constexpr int INF_COORD = 2'000'000'000; /* Maintains a nondecreasing array under range assignment and supports: - assigning a value to an interval - finding the first position whose value is >= a threshold */ class BoundTree { int n; vector<int> mx, lazy; void apply(int v, int value) { mx[v] = value; lazy[v] = value; } void push(int v) { if (lazy[v] == -1) return; apply(v * 2, lazy[v]); apply(v * 2 + 1, lazy[v]); lazy[v] = -1; } void assignRec(int v, int l, int r, int ql, int qr, int value) { if (ql <= l && r <= qr) { apply(v, value); return; } push(v); int m = (l + r) / 2; if (ql <= m) assignRec(v * 2, l, m, ql, qr, value); if (qr > m) assignRec(v * 2 + 1, m + 1, r, ql, qr, value); mx[v] = max(mx[v * 2], mx[v * 2 + 1]); } public: BoundTree(int n_, int initial) : n(n_), mx(4 * n_, initial), lazy(4 * n_, initial) {} void assignRange(int l, int r, int value) { if (l <= r) assignRec(1, 0, n - 1, l, r, value); } int firstAtLeast(int value) { if (mx[1] < value) return n; int v = 1, l = 0, r = n - 1; while (l < r) { push(v); int m = (l + r) / 2; if (mx[v * 2] >= value) { v = v * 2; r = m; } else { v = v * 2 + 1; l = m + 1; } } return l; } }; /* For each possible x-axis turning point a, maintains the best path using a. States: middle: L <= Y <= U, so the best y-axis turning point is Y lower: L > Y, so the best y-axis turning point is L upper: U < Y, so the best y-axis turning point is U For a fixed lower/upper bound z, the cost |X-a| + sqrt(a^2+z^2) + constant decreases for a < X and increases for a >= X. Thus, among active positions in a segment, only the largest active a < X and the smallest active a >= X are needed to compute the minimum. */ class StateTree { struct Node { double middle = INF_COST; double lower = INF_COST; double upper = INF_COST; int lowerLeft = -1; int lowerRight = -1; int upperLeft = -1; int upperRight = -1; int lowerTag = -1; int upperTag = -1; }; int n, X, Y; const vector<int>& coord; vector<Node> tree; static int minValid(int a, int b) { if (a == -1) return b; if (b == -1) return a; return min(a, b); } double middleCost(int index) const { double a = coord[index]; return fabs(a - X) + sqrt(a * a + 1.0 * Y * Y); } double lowerCost(int index, int bound) const { double a = coord[index]; return fabs(a - X) + sqrt(a * a + 1.0 * bound * bound) + (bound - Y); } double upperCost(int index, int bound) const { double a = coord[index]; return fabs(a - X) + sqrt(a * a + 1.0 * bound * bound) + (Y - bound); } void pull(int v) { const Node& left = tree[v * 2]; const Node& right = tree[v * 2 + 1]; Node& cur = tree[v]; cur.middle = min(left.middle, right.middle); cur.lower = min(left.lower, right.lower); cur.upper = min(left.upper, right.upper); cur.lowerLeft = max(left.lowerLeft, right.lowerLeft); cur.lowerRight = minValid(left.lowerRight, right.lowerRight); cur.upperLeft = max(left.upperLeft, right.upperLeft); cur.upperRight = minValid(left.upperRight, right.upperRight); } void applyLower(int v, int bound) { Node& cur = tree[v]; if (cur.lowerLeft == -1 && cur.lowerRight == -1) { cur.lowerTag = -1; cur.lower = INF_COST; return; } cur.lowerTag = bound; cur.lower = INF_COST; if (cur.lowerLeft != -1) cur.lower = min(cur.lower, lowerCost(cur.lowerLeft, bound)); if (cur.lowerRight != -1) cur.lower = min(cur.lower, lowerCost(cur.lowerRight, bound)); } void applyUpper(int v, int bound) { Node& cur = tree[v]; if (cur.upperLeft == -1 && cur.upperRight == -1) { cur.upperTag = -1; cur.upper = INF_COST; return; } cur.upperTag = bound; cur.upper = INF_COST; if (cur.upperLeft != -1) cur.upper = min(cur.upper, upperCost(cur.upperLeft, bound)); if (cur.upperRight != -1) cur.upper = min(cur.upper, upperCost(cur.upperRight, bound)); } void push(int v) { Node& cur = tree[v]; if (cur.lowerTag != -1) { applyLower(v * 2, cur.lowerTag); applyLower(v * 2 + 1, cur.lowerTag); cur.lowerTag = -1; } if (cur.upperTag != -1) { applyUpper(v * 2, cur.upperTag); applyUpper(v * 2 + 1, cur.upperTag); cur.upperTag = -1; } } void build(int v, int l, int r) { if (l == r) { tree[v].middle = middleCost(l); return; } int m = (l + r) / 2; build(v * 2, l, m); build(v * 2 + 1, m + 1, r); pull(v); } void assignLowerRec(int v, int l, int r, int ql, int qr, int bound) { if (tree[v].lowerLeft == -1 && tree[v].lowerRight == -1) return; if (ql <= l && r <= qr) { applyLower(v, bound); return; } push(v); int m = (l + r) / 2; if (ql <= m) assignLowerRec(v * 2, l, m, ql, qr, bound); if (qr > m) assignLowerRec(v * 2 + 1, m + 1, r, ql, qr, bound); pull(v); } void assignUpperRec(int v, int l, int r, int ql, int qr, int bound) { if (tree[v].upperLeft == -1 && tree[v].upperRight == -1) return; if (ql <= l && r <= qr) { applyUpper(v, bound); return; } push(v); int m = (l + r) / 2; if (ql <= m) assignUpperRec(v * 2, l, m, ql, qr, bound); if (qr > m) assignUpperRec(v * 2 + 1, m + 1, r, ql, qr, bound); pull(v); } void activateLowerRec(int v, int l, int r, int index, int bound) { if (l == r) { Node& cur = tree[v]; cur.middle = INF_COST; cur.upper = INF_COST; cur.upperLeft = cur.upperRight = -1; cur.upperTag = -1; cur.lowerLeft = (coord[index] < X ? index : -1); cur.lowerRight = (coord[index] >= X ? index : -1); cur.lower = lowerCost(index, bound); cur.lowerTag = bound; return; } push(v); int m = (l + r) / 2; if (index <= m) activateLowerRec(v * 2, l, m, index, bound); else activateLowerRec(v * 2 + 1, m + 1, r, index, bound); pull(v); } void activateUpperRec(int v, int l, int r, int index, int bound) { if (l == r) { Node& cur = tree[v]; cur.middle = INF_COST; cur.lower = INF_COST; cur.lowerLeft = cur.lowerRight = -1; cur.lowerTag = -1; cur.upperLeft = (coord[index] < X ? index : -1); cur.upperRight = (coord[index] >= X ? index : -1); cur.upper = upperCost(index, bound); cur.upperTag = bound; return; } push(v); int m = (l + r) / 2; if (index <= m) activateUpperRec(v * 2, l, m, index, bound); else activateUpperRec(v * 2 + 1, m + 1, r, index, bound); pull(v); } void deactivateRec(int v, int l, int r, int index) { if (l == r) { Node& cur = tree[v]; cur.middle = cur.lower = cur.upper = INF_COST; cur.lowerLeft = cur.lowerRight = -1; cur.upperLeft = cur.upperRight = -1; cur.lowerTag = cur.upperTag = -1; return; } push(v); int m = (l + r) / 2; if (index <= m) deactivateRec(v * 2, l, m, index); else deactivateRec(v * 2 + 1, m + 1, r, index); pull(v); } public: StateTree(const vector<int>& coordinates, int X_, int Y_) : n((int)coordinates.size()), X(X_), Y(Y_), coord(coordinates), tree(4 * n) { build(1, 0, n - 1); } void assignLower(int l, int r, int bound) { if (l <= r) assignLowerRec(1, 0, n - 1, l, r, bound); } void assignUpper(int l, int r, int bound) { if (l <= r) assignUpperRec(1, 0, n - 1, l, r, bound); } void activateLower(int index, int bound) { activateLowerRec(1, 0, n - 1, index, bound); } void activateUpper(int index, int bound) { activateUpperRec(1, 0, n - 1, index, bound); } void deactivate(int index) { deactivateRec(1, 0, n - 1, index); } double best() const { return min(tree[1].middle, min(tree[1].lower, tree[1].upper)); } }; class PhotoSolver { int X, Y; vector<int> coord; BoundTree lowerBounds; BoundTree upperBounds; StateTree states; set<int> middle, lower, upper; void invalidateIn(set<int>& indices, int l, int r) { auto it = indices.lower_bound(l); while (it != indices.end() && *it <= r) { int index = *it; it = indices.erase(it); states.deactivate(index); } } void invalidateRange(int l, int r) { if (l > r) return; invalidateIn(middle, l, r); invalidateIn(lower, l, r); invalidateIn(upper, l, r); } void moveMiddleToLower(int l, int r, int bound) { auto it = middle.lower_bound(l); while (it != middle.end() && *it <= r) { int index = *it; it = middle.erase(it); states.activateLower(index, bound); lower.insert(index); } } void moveMiddleToUpper(int l, int r, int bound) { auto it = middle.lower_bound(l); while (it != middle.end() && *it <= r) { int index = *it; it = middle.erase(it); states.activateUpper(index, bound); upper.insert(index); } } public: PhotoSolver(const vector<int>& coordinates, int X_, int Y_) : X(X_), Y(Y_), coord(coordinates), lowerBounds((int)coord.size(), 0), upperBounds((int)coord.size(), INF_COORD), states(coord, X, Y) { for (int i = 0; i < (int)coord.size(); ++i) middle.insert(middle.end(), i); } void addObstacle(int position, int y) { /* For a > x: L(a) = max(L(a), y). L is nondecreasing, so the positions where L actually changes form one interval. */ int firstLowerAtLeast = lowerBounds.firstAtLeast(y); int affectedLeft = position + 1; int affectedRight = firstLowerAtLeast - 1; if (affectedLeft <= affectedRight) { lowerBounds.assignRange(affectedLeft, affectedRight, y); // New interval [L,U] is invalid exactly where U < y. int firstUpperAtLeast = upperBounds.firstAtLeast(y); invalidateRange(affectedLeft, min(affectedRight, firstUpperAtLeast - 1)); int validLeft = max(affectedLeft, firstUpperAtLeast); if (validLeft <= affectedRight && y > Y) { states.assignLower(validLeft, affectedRight, y); moveMiddleToLower(validLeft, affectedRight, y); } } /* For a < x: U(a) = min(U(a), y). U is nondecreasing, so the positions where U actually changes also form one interval. */ int firstUpperGreater = upperBounds.firstAtLeast(y + 1); int affectedUL = firstUpperGreater; int affectedUR = position - 1; if (affectedUL <= affectedUR) { upperBounds.assignRange(affectedUL, affectedUR, y); // New interval [L,U] is invalid exactly where L > y. int firstLowerGreater = lowerBounds.firstAtLeast(y + 1); invalidateRange(max(affectedUL, firstLowerGreater), affectedUR); int validRight = min(affectedUR, firstLowerGreater - 1); if (affectedUL <= validRight && y < Y) { states.assignUpper(affectedUL, validRight, y); moveMiddleToUpper(affectedUL, validRight, y); } } } double best() const { return states.best(); } }; struct Obstacle { int s, x, y, position; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, T; cin >> N >> T; int X, Y; cin >> X >> Y; vector<Obstacle> obstacles(N); vector<int> coordinates; coordinates.reserve(N + 1); coordinates.push_back(X); for (auto& obstacle : obstacles) { cin >> obstacle.s >> obstacle.x >> obstacle.y; coordinates.push_back(obstacle.x); } sort(coordinates.begin(), coordinates.end()); coordinates.erase(unique(coordinates.begin(), coordinates.end()), coordinates.end()); for (auto& obstacle : obstacles) { obstacle.position = int(lower_bound(coordinates.begin(), coordinates.end(), obstacle.x) - coordinates.begin()); } PhotoSolver solver(coordinates, X, Y); int nextObstacle = 0; for (int t = 0; t < T; ++t) { while (nextObstacle < N && obstacles[nextObstacle].s <= t) { solver.addObstacle(obstacles[nextObstacle].position, obstacles[nextObstacle].y); ++nextObstacle; } /* Every candidate length is an integer plus sqrt(integer). For values at most 2e12, a non-integral square root differs from the nearest integer by more than 3.5e-7, so this small epsilon only compensates for floating-point rounding. */ long long answer = (long long)floor(solver.best() + 1e-8); cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; static ll floorSqrt(ll n) { ll r = (ll)sqrtl((long double)n); while ((r + 1) * (r + 1) <= n) ++r; while (r * r > n) --r; return r; } /* Stores active points, indexed by compressed x-coordinate. For a range, returns: - the active point with maximum y - the active point with minimum y */ class PointSegmentTree { int base; vector<int> maxId, minId; const vector<int>& y; int betterMax(int a, int b) const { if (a == -1) return b; if (b == -1) return a; return y[a] > y[b] ? a : b; } int betterMin(int a, int b) const { if (a == -1) return b; if (b == -1) return a; return y[a] < y[b] ? a : b; } public: PointSegmentTree(int n, const vector<int>& values) : y(values) { base = 1; while (base < n) base <<= 1; maxId.assign(2 * base, -1); minId.assign(2 * base, -1); } void insert(int position, int id) { int p = base + position; maxId[p] = minId[p] = id; for (p >>= 1; p > 0; p >>= 1) { maxId[p] = betterMax(maxId[2 * p], maxId[2 * p + 1]); minId[p] = betterMin(minId[2 * p], minId[2 * p + 1]); } } // Query [left, right). int queryMax(int left, int right) const { int answer = -1; for (left += base, right += base; left < right; left >>= 1, right >>= 1) { if (left & 1) answer = betterMax(answer, maxId[left++]); if (right & 1) answer = betterMax(answer, maxId[--right]); } return answer; } int queryMin(int left, int right) const { int answer = -1; for (left += base, right += base; left < right; left >>= 1, right >>= 1) { if (left & 1) answer = betterMin(answer, minId[left++]); if (right & 1) answer = betterMin(answer, minId[--right]); } return answer; } }; /* Stores the minimum candidate distance at every possible boundary. Key 0: outer boundary before the first component. Key root id: boundary immediately after that component. Key N+1: outer boundary after the last component. */ class MinSegmentTree { public: static constexpr int INF = 1'000'000'000; private: int base; vector<int> tree; public: explicit MinSegmentTree(int n) { base = 1; while (base < n) base <<= 1; tree.assign(2 * base, INF); } void setPoint(int position, int value) { int p = base + position; tree[p] = value; for (p >>= 1; p > 0; p >>= 1) { tree[p] = min(tree[2 * p], tree[2 * p + 1]); } } int minimum() const { return tree[1]; } }; class DynamicSolver { struct Component { int lx = 0, rx = 0; int ly = 0, ry = 0; int lxId = 0, rxId = 0; int lyId = 0, ryId = 0; int prv = -1, nxt = -1; }; struct Candidate { int coordinate; int pointId; // 0 means X or Y, rather than an obstacle endpoint. }; int N, X, Y, M; const vector<int>& y; const vector<int>& position; vector<int> parent, dsuSize; vector<Component> component; vector<unsigned char> active; // Components ordered by their minimum x-coordinate. map<int, int> componentByLx; PointSegmentTree pointTree; MinSegmentTree boundaryTree; vector<int> mergeBuffer; int findRoot(int v) { while (parent[v] != v) { parent[v] = parent[parent[v]]; v = parent[v]; } return v; } static void absorb(Component& result, const Component& other) { if (other.lx < result.lx) { result.lx = other.lx; result.lxId = other.lxId; } if (other.rx > result.rx) { result.rx = other.rx; result.rxId = other.rxId; } if (other.ly < result.ly) { result.ly = other.ly; result.lyId = other.lyId; } if (other.ry > result.ry) { result.ry = other.ry; result.ryId = other.ryId; } } int evaluateCandidates(const Candidate* p, int np, const Candidate* q, int nq) const { int answer = MinSegmentTree::INF; for (int i = 0; i < np; ++i) { for (int j = 0; j < nq; ++j) { // Using the two endpoints of the same sight would overlap // that sight, which is not a valid transversal. if (p[i].pointId != 0 && p[i].pointId == q[j].pointId) { continue; } ll squared = 1LL * p[i].coordinate * p[i].coordinate + 1LL * q[j].coordinate * q[j].coordinate; ll root = floorSqrt(squared); ll distance = llabs((ll)X - p[i].coordinate) + llabs((ll)Y - q[j].coordinate) + root; answer = min(answer, (int)distance); } } return answer; } // Boundary between two consecutive components. int middleBoundaryCost(int lower, int upper) const { const Component& a = component[lower]; const Component& b = component[upper]; Candidate p[3], q[3]; int np = 0, nq = 0; p[np++] = {a.rx, a.rxId}; p[np++] = {b.lx, b.lxId}; if (a.rx < X && X < b.lx) { p[np++] = {X, 0}; } q[nq++] = {a.ry, a.ryId}; q[nq++] = {b.ly, b.lyId}; if (a.ry < Y && Y < b.ly) { q[nq++] = {Y, 0}; } return evaluateCandidates(p, np, q, nq); } // Boundary before the first component. int leftBoundaryCost(int first) const { const Component& c = component[first]; Candidate p[2], q[2]; int np = 0, nq = 0; p[np++] = {c.lx, c.lxId}; if (X < c.lx) p[np++] = {X, 0}; q[nq++] = {c.ly, c.lyId}; if (Y < c.ly) q[nq++] = {Y, 0}; return evaluateCandidates(p, np, q, nq); } // Boundary after the last component. int rightBoundaryCost(int last) const { const Component& c = component[last]; Candidate p[2], q[2]; int np = 0, nq = 0; p[np++] = {c.rx, c.rxId}; if (X > c.rx) p[np++] = {X, 0}; q[nq++] = {c.ry, c.ryId}; if (Y > c.ry) q[nq++] = {Y, 0}; return evaluateCandidates(p, np, q, nq); } void refreshOuterBoundaries() { if (componentByLx.empty()) { boundaryTree.setPoint(0, MinSegmentTree::INF); boundaryTree.setPoint(N + 1, MinSegmentTree::INF); return; } int first = componentByLx.begin()->second; int last = prev(componentByLx.end())->second; boundaryTree.setPoint(0, leftBoundaryCost(first)); boundaryTree.setPoint(N + 1, rightBoundaryCost(last)); } void insertSingleton(int id, int x, int y) { auto it = componentByLx.lower_bound(x); int after = (it == componentByLx.end() ? -1 : it->second); int before = -1; if (it != componentByLx.begin()) { before = prev(it)->second; } // Remove the old before -> after boundary. if (before != -1) { boundaryTree.setPoint(before, MinSegmentTree::INF); } Component current; current.lx = current.rx = x; current.ly = current.ry = y; current.lxId = current.rxId = current.lyId = current.ryId = id; current.prv = before; current.nxt = after; component[id] = current; active[id] = true; if (before != -1) component[before].nxt = id; if (after != -1) component[after].prv = id; componentByLx[x] = id; if (before != -1) { boundaryTree.setPoint(before, middleBoundaryCost(before, id)); } if (after != -1) { boundaryTree.setPoint(id, middleBoundaryCost(id, after)); } refreshOuterBoundaries(); } void mergeRange(int left, int right, int id, int x, int y) { mergeBuffer.clear(); int current = left; while (true) { mergeBuffer.push_back(current); if (current == right) break; current = component[current].nxt; } int before = component[left].prv; int after = component[right].nxt; // Remove all boundaries touching the merged range. if (before != -1) { boundaryTree.setPoint(before, MinSegmentTree::INF); } for (int c : mergeBuffer) { boundaryTree.setPoint(c, MinSegmentTree::INF); } Component merged; merged.lx = merged.rx = x; merged.ly = merged.ry = y; merged.lxId = merged.rxId = merged.lyId = merged.ryId = id; int totalSize = 1; for (int c : mergeBuffer) { absorb(merged, component[c]); totalSize += dsuSize[c]; componentByLx.erase(component[c].lx); parent[c] = id; active[c] = false; } dsuSize[id] = totalSize; merged.prv = before; merged.nxt = after; component[id] = merged; active[id] = true; if (before != -1) component[before].nxt = id; if (after != -1) component[after].prv = id; componentByLx[merged.lx] = id; if (before != -1) { boundaryTree.setPoint(before, middleBoundaryCost(before, id)); } if (after != -1) { boundaryTree.setPoint(id, middleBoundaryCost(id, after)); } refreshOuterBoundaries(); } public: DynamicSolver(int n, int startX, int targetY, const vector<int>& yValues, const vector<int>& positions, int coordinateCount) : N(n), X(startX), Y(targetY), M(coordinateCount), y(yValues), position(positions), parent(n + 1), dsuSize(n + 1, 1), component(n + 1), active(n + 1, false), pointTree(coordinateCount, yValues), boundaryTree(n + 2) { iota(parent.begin(), parent.end(), 0); mergeBuffer.reserve(n); } void insertPoint(int id) { int x = position[id]; int px = componentCoordinates(id); /* A new point (px, py) crosses an old point in either of two ways: old.x < px and old.y > py old.x > px and old.y < py */ int northWestWitness = pointTree.queryMax(0, x); int southEastWitness = pointTree.queryMin(x + 1, M); int left = -1, right = -1; // Components containing a north-west crossing point. if (northWestWitness != -1 && y[northWestWitness] > componentCoordinates(id)) { int root = findRoot(northWestWitness); int first = root; while (component[first].prv != -1 && component[component[first].prv].ry > componentCoordinates(id)) { first = component[first].prv; } left = first; right = root; } // Components containing a south-east crossing point. if (southEastWitness != -1 && y[southEastWitness] < componentCoordinates(id)) { int root = findRoot(southEastWitness); int last = root; while (component[last].nxt != -1 && component[component[last].nxt].ly < componentCoordinates(id)) { last = component[last].nxt; } if (left == -1) { left = root; right = last; } else { if (component[root].lx < component[left].lx) { left = root; } if (component[last].lx > component[right].lx) { right = last; } } } if (left == -1) { insertSingleton(id, componentCoordinates(id), componentCoordinates(id)); } else { mergeRange(left, right, id, componentCoordinates(id), componentCoordinates(id)); } pointTree.insert(x, id); } int answer() const { if (componentByLx.empty()) { return (int)floorSqrt(1LL * X * X + 1LL * Y * Y); } return boundaryTree.minimum(); } private: // Kept separate so the insertion code above remains readable. int componentCoordinates(int id) const { return originalY[id]; } const vector<int>& originalY; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, T; cin >> N >> T; int X, Y; cin >> X >> Y; vector<int> s(N + 1), x(N + 1), y(N + 1); vector<int> compressedX; compressedX.reserve(N + 1); compressedX.push_back(X); for (int i = 1; i <= N; ++i) { cin >> s[i] >> x[i] >> y[i]; compressedX.push_back(x[i]); } sort(compressedX.begin(), compressedX.end()); compressedX.erase(unique(compressedX.begin(), compressedX.end()), compressedX.end()); vector<int> position(N + 1); for (int i = 1; i <= N; ++i) { position[i] = int(lower_bound(compressedX.begin(), compressedX.end(), x[i]) - compressedX.begin()); } DynamicSolver solver(N, X, Y, y, position, int(compressedX.size())); int nextCow = 1; for (int t = 0; t < T; ++t) { while (nextCow <= N && s[nextCow] <= t) { solver.insertPoint(nextCow); ++nextCow; } cout << solver.answer() << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; struct Event { int s, x, y; }; struct Block { int firstY = 0, lastY = 0; int minX = 0, maxX = 0; int size = 0; ll cost = 0; bool inCostSet = false; }; class Solver { static constexpr ll INF = (1LL << 60); int X, Y; vector<Block> blocks; // Ordered by the smallest y-coordinate in each block. map<int, int> order; // One entry per block: (answer contributed by this block, block ID). set<pair<ll, int>> costSet; // Active obstacles with y < Y and y > Y, respectively. priority_queue<int> belowMax; priority_queue<int, vector<int>, greater<int>> aboveMin; static ll integerSqrt(ll n) { ll r = static_cast<ll>(sqrt(static_cast<long double>(n))); while ((r + 1) * (r + 1) <= n) ++r; while (r * r > n) --r; return r; } ll pathCost(ll a, ll b) const { return llabs(static_cast<ll>(X) - a) + llabs(static_cast<ll>(Y) - b) + integerSqrt(a * a + b * b); } // For a feasible interval [L, U], an optimal a is X clamped to it. ll optimalA(ll L, ll U) const { if (L > U) return -1; if (static_cast<ll>(X) < L) return L; if (static_cast<ll>(X) > U) return U; return X; } ll computeBlockCost(int id) const { const Block &b = blocks[id]; auto it = order.find(b.firstY); int prevId = -1, nextId = -1; if (it != order.begin()) prevId = prev(it)->second; auto nit = next(it); if (nit != order.end()) nextId = nit->second; ll answer = INF; if (b.size == 1) { // The block's own obstacle is excluded because its y-coordinate // equals the candidate b. ll L = (prevId == -1 ? 0 : blocks[prevId].maxX); ll U = (nextId == -1 ? INF : blocks[nextId].minX); ll a = optimalA(L, U); if (a >= 0) answer = min(answer, pathCost(a, b.firstY)); } else { // Candidate using the first obstacle in the block. { ll L = (prevId == -1 ? 0 : blocks[prevId].maxX); ll U = b.minX; ll a = optimalA(L, U); if (a >= 0) answer = min(answer, pathCost(a, b.firstY)); } // Candidate using the last obstacle in the block. { ll L = b.maxX; ll U = (nextId == -1 ? INF : blocks[nextId].minX); ll a = optimalA(L, U); if (a >= 0) answer = min(answer, pathCost(a, b.lastY)); } } return answer; } void refreshBlock(int id) { Block &b = blocks[id]; if (b.inCostSet) { costSet.erase({b.cost, id}); } b.cost = computeBlockCost(id); costSet.insert({b.cost, id}); b.inCostSet = true; } public: Solver(int startX, int targetY, int maxN) : X(startX), Y(targetY) { blocks.reserve(maxN + 1); } void insertObstacle(int x, int y) { if (y < Y) { belowMax.push(x); } else { aboveMin.push(x); } const int newId = static_cast<int>(blocks.size()); blocks.emplace_back(); Block merged; merged.firstY = merged.lastY = y; merged.minX = merged.maxX = x; merged.size = 1; auto lower = order.lower_bound(y); // Does the new y-coordinate lie inside an existing block's y-range? int containingId = -1; if (lower != order.begin()) { auto p = prev(lower); if (blocks[p->second].lastY > y) { containingId = p->second; } } vector<int> removed; int outsidePrev = -1, outsideNext = -1; bool hasRange = false; map<int, int>::iterator leftMost, rightMost; if (containingId != -1) { auto anchor = order.find(blocks[containingId].firstY); leftMost = anchor; while (leftMost != order.begin()) { auto p = prev(leftMost); if (blocks[p->second].maxX <= x) break; leftMost = p; } auto after = next(anchor); while (after != order.end() && blocks[after->second].minX < x) { ++after; } rightMost = prev(after); hasRange = true; } else { bool leftTouched = false, rightTouched = false; auto lit = lower; while (lit != order.begin()) { auto p = prev(lit); if (blocks[p->second].maxX <= x) break; lit = p; leftTouched = true; } auto rit = lower; while (rit != order.end() && blocks[rit->second].minX < x) { ++rit; rightTouched = true; } if (leftTouched) { leftMost = lit; rightMost = lit; hasRange = true; } if (rightTouched) { rightMost = prev(rit); if (!leftTouched) leftMost = rightMost; hasRange = true; } } if (!hasRange) { if (lower != order.begin()) { outsidePrev = prev(lower)->second; } if (lower != order.end()) { outsideNext = lower->second; } blocks[newId] = merged; order.emplace(y, newId); refreshBlock(newId); if (outsidePrev != -1) refreshBlock(outsidePrev); if (outsideNext != -1) refreshBlock(outsideNext); return; } if (leftMost != order.begin()) { outsidePrev = prev(leftMost)->second; } auto afterRight = next(rightMost); if (afterRight != order.end()) { outsideNext = afterRight->second; } for (auto it = leftMost;; ++it) { removed.push_back(it->second); if (it == rightMost) break; } for (int id : removed) { const Block &b = blocks[id]; merged.minX = min(merged.minX, b.minX); merged.maxX = max(merged.maxX, b.maxX); merged.firstY = min(merged.firstY, b.firstY); merged.lastY = max(merged.lastY, b.lastY); merged.size += b.size; } for (int id : removed) { if (blocks[id].inCostSet) { costSet.erase({blocks[id].cost, id}); blocks[id].inCostSet = false; } order.erase(blocks[id].firstY); } blocks[newId] = merged; order.emplace(merged.firstY, newId); refreshBlock(newId); if (outsidePrev != -1) refreshBlock(outsidePrev); if (outsideNext != -1) refreshBlock(outsideNext); } ll answer() const { // Going through the origin is always possible. ll result = static_cast<ll>(X) + Y; if (!costSet.empty()) { result = min(result, costSet.begin()->first); } // Candidate whose y-axis endpoint is exactly Y. ll L = belowMax.empty() ? 0 : belowMax.top(); ll U = aboveMin.empty() ? INF : aboveMin.top(); ll a = optimalA(L, U); if (a >= 0) { result = min(result, pathCost(a, Y)); } return result; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N, T; cin >> N >> T; int X, Y; cin >> X >> Y; vector<Event> events(N); for (auto &e : events) { cin >> e.s >> e.x >> e.y; } Solver solver(X, Y, N); int ptr = 0; for (int t = 0; t < T; ++t) { while (ptr < N && events[ptr].s <= t) { solver.insertObstacle(events[ptr].x, events[ptr].y); ++ptr; } cout << solver.answer() << '\n'; } return 0; }