2022 Problems
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+26
- 2022/finals/1142476319774543.jpgAdded
- 2022/finals/1175696903384597.jpgAdded
- 2022/finals/1310493279783732.jpgAdded
- 2022/finals/1327255974690671.jpgAdded
- 2022/finals/2468652649959145.jpgAdded
- 2022/finals/504150738360453.jpgAdded
- 2022/finals/547949757342773.jpgAdded
- 2022/finals/556593865835592.jpgAdded
- 2022/finals/6502772429739994.jpgAdded
- 2022/finals/650302073463012.jpgAdded
- 2022/finals/853886435922998.jpgAdded
- 2022/finals/876374553707415.jpgAdded
- 2022/finals/alphabet_adventuring.cppAdded+425
- 2022/finals/alphabet_adventuring.inAdded+3
- 2022/finals/alphabet_adventuring.mdAdded+72
- 2022/finals/alphabet_adventuring.outAdded
- 2022/finals/alphabet_adventuring_sol.mdAdded+25
- 2022/finals/cup_counterbalancing.inAdded+42
- 2022/finals/cup_counterbalancing.javaAdded+397
- 2022/finals/cup_counterbalancing.mdAdded+34
- 2022/finals/cup_counterbalancing.outAdded+7
- 2022/finals/cup_counterbalancing_sol.mdAdded+18
- 2022/finals/emerald_exhibiting.cppAdded+94
- 2022/finals/emerald_exhibiting.inAdded+111
- 2022/finals/emerald_exhibiting.mdAdded+47
- 2022/finals/emerald_exhibiting.outAdded+110
- 2022/finals/emerald_exhibiting_sol.mdAdded+18
- 2022/finals/hazelnut_harvesting.cppAdded+356
- 2022/finals/hazelnut_harvesting.inAdded+3
- 2022/finals/hazelnut_harvesting.mdAdded+41
- 2022/finals/hazelnut_harvesting.outAdded+160
- 2022/finals/hazelnut_harvesting_sol.mdAdded+21
- 2022/finals/ml_modeling.cppAdded+102
- 2022/finals/ml_modeling.inAdded+3
- 2022/finals/ml_modeling.mdAdded+51
- 2022/finals/ml_modeling.outAdded+1000
- 2022/finals/ml_modeling_sol.mdAdded+11
- 2022/finals/tile_transposing.cppAdded+382
- 2022/finals/tile_transposing.inAdded+3
- 2022/finals/tile_transposing.mdAdded+61
- 2022/finals/tile_transposing.outAdded+105
- 2022/finals/tile_transposing_sol.mdAdded+58
- 2022/quals/1183048075593188.jpgAdded
- 2022/quals/1264108514364518.jpgAdded
- 2022/quals/356437426702208.jpgAdded
- 2022/quals/459254706243127.jpgAdded
- 2022/quals/5118404751621442.jpgAdded
- 2022/quals/545859687328272.jpgAdded
- 2022/quals/569216148234749.jpgAdded
111 unmodified lines112113114115116117118119120121122123124125126127128129130131132133134135136137138139140111 unmodified lines2023/round2/wiki_race.in filter=lfs diff=lfs merge=lfs -text2023/round3/double_stars.in filter=lfs diff=lfs merge=lfs -text2023/round3/similar_ships.in filter=lfs diff=lfs merge=lfs -text2022/finals/alphabet_adventuring.in filter=lfs diff=lfs merge=lfs -text2022/finals/hazelnut_harvesting.in filter=lfs diff=lfs merge=lfs -text2022/finals/ml_modeling.in filter=lfs diff=lfs merge=lfs -text2022/finals/tile_transposing.in filter=lfs diff=lfs merge=lfs -text2022/quals/second_flight.in filter=lfs diff=lfs merge=lfs -text2022/quals/second_flight.out filter=lfs diff=lfs merge=lfs -text2022/quals/second_second_friend.in filter=lfs diff=lfs merge=lfs -text2022/quals/second_second_friend.out filter=lfs diff=lfs merge=lfs -text2022/round1/consecutive_cuts_ch1.in filter=lfs diff=lfs merge=lfs -text2022/round1/consecutive_cuts_ch2.in filter=lfs diff=lfs merge=lfs -text2022/round1/lemonade_life.in filter=lfs diff=lfs merge=lfs -text2022/round1/watering_well_ch1.in filter=lfs diff=lfs merge=lfs -text2022/round1/watering_well_ch2.in filter=lfs diff=lfs merge=lfs -text2022/round2/balance_scale.in filter=lfs diff=lfs merge=lfs -text2022/round2/balance_sheet.in filter=lfs diff=lfs merge=lfs -text2022/round2/perfectly_balanced_ch1.in filter=lfs diff=lfs merge=lfs -text2022/round2/perfectly_balanced_ch2.in filter=lfs diff=lfs merge=lfs -text2022/round2/work_life_balance_ch1.in filter=lfs diff=lfs merge=lfs -text2022/round2/work_life_balance_ch2.in filter=lfs diff=lfs merge=lfs -text2022/round3/first_time_ch1.in filter=lfs diff=lfs merge=lfs -text2022/round3/first_time_ch2.in filter=lfs diff=lfs merge=lfs -text2022/round3/fourth_player.in filter=lfs diff=lfs merge=lfs -text2022/round3/second_mistake.in filter=lfs diff=lfs merge=lfs -text2022/round3/third_trie.in filter=lfs diff=lfs merge=lfs -text2022/round3/zero_crossings_ch1.in filter=lfs diff=lfs merge=lfs -text2022/round3/zero_crossings_ch2.in filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425#include <algorithm>#include <iostream>#include <utility>#include <vector>using namespace std;
using pii = pair<int, int>;
struct Req { int ind, t, x, y; vector<int> alph;};
int pair_cnt;vector<vector<int>> pair_map;
int N, M, Q;vector<pii> edges;vector<vector<pii>> g;vector<Req> a;vector<int> ans, lnks, lnks_z, lnk_jump, d, par, par_z;vector<vector<int>> top_links, bot_links, bu_links;
vector<int> dsu;
int get_dsu_parent(int x) { if (dsu[x] == dsu[dsu[x]]) { return dsu[x]; } return dsu[x] = get_dsu_parent(dsu[x]);}
int get_top_link(int edge_ind, int pair_ind) { if (top_links[edge_ind][pair_ind] == edge_ind) { return edge_ind; } return get_top_link(top_links[edge_ind][pair_ind], pair_ind);}
int get_edge_ind(int x, int y) { pii edge(x, y); int l = 0, r = M - 1; while (l <= r) { int mid = (l + r) >> 1; if (edges[mid] == edge) { return mid; } if (edges[mid] < edge) { l = mid + 1; } else { r = mid - 1; } } return -1;}
void precalc() { pair_map.assign(26, vector<int>(26, -1)); pair_cnt = 0; for (int z1 = 0; z1 < 26; z1++) { for (int z2 = z1 + 1; z2 < 26; z2++) { pair_map[z1][z2] = pair_cnt++; pair_map[z2][z1] = pair_cnt++; } }}
void add_edge(int x, int y, int z) { edges.push_back({x, y}); g[x].push_back({y, z});}
int dfs_lnks(int x, int p) { par[x] = p; lnk_jump[x] = x; if (x == p) { d[x] = 0; } else { d[x] = d[p] + 1; } lnks[x] = -1; lnks_z[x] = -1; int best = 0, total = 0; for (auto [y, z] : g[x]) { if (y == p) { par_z[x] = z; continue; } int cur = dfs_lnks(y, x); total += cur; if (cur > best) { best = cur; lnk_jump[x] = lnk_jump[y]; lnks[x] = y; lnks_z[x] = z; } } return total + 1;}
void run_precalc_top(int x, int p) { if (x != p) { int edge_ind = get_edge_ind(x, p); if (p == par[p]) { top_links[edge_ind].assign(pair_cnt, edge_ind); } else { int par_edge_ind = get_edge_ind(p, par[p]); top_links[edge_ind] = top_links[par_edge_ind]; }
if (par[p] != p) { int ppz = par_z[p]; for (auto [y, z] : g[p]) { if (y == par[p] || y == x) { continue; } top_links[edge_ind][pair_map[z][ppz]] = edge_ind; } } } for (int i = 0; i < (int)g[x].size(); i++) { int y = g[x][i].first; if (y == p) { continue; } run_precalc_top(y, x); }}
void run_precalc_bot(int x, int p) { for (auto [y, _] : g[x]) { if (y != p) { run_precalc_bot(y, x); } } int ly = lnks[x], lz = lnks_z[x]; if (ly != -1) { bot_links[x] = bot_links[ly]; for (auto [y, z] : g[x]) { if (y == ly || y == p) { continue; } bot_links[x][pair_map[z][lz]] = x; } } else { bot_links[x].assign(pair_cnt, x); }}
void binary_uplifting() { int sz = (int)g.size(); int maxp = 1; while ((1 << maxp) < sz) { ++maxp; } ++maxp; bu_links.assign(maxp, vector<int>(sz)); for (int i = 0; i < sz; i++) { bu_links[0][i] = par[i]; } for (int p = 1; p < maxp; p++) { for (int i = 0; i < sz; i++) { bu_links[p][i] = bu_links[p - 1][bu_links[p - 1][i]]; } }}
void init() { int x = 0, y = 0, z = 0; char c = 0; g.clear(); edges.clear(); edges.reserve(N << 2); cin >> N; g.resize(N); for (int i = 1; i < N; i++) { cin >> x >> y >> c; --x, --y; z = (int)(c - 'A'); add_edge(x, y, z); add_edge(y, x, z); } int t = 0; string s; vector<int> alph; cin >> Q; a.resize(Q); for (int i = 0; i < Q; i++) { Req &r = a[i]; cin >> t; --t; r.ind = i; r.t = t; if (t) { cin >> x >> y >> s; --x; alph.resize(s.length()); for (int i = 0; i < (int)s.length(); i++) { alph[i] = (int)(s[i] - 'A'); } r.x = x; r.y = y; r.alph = alph; } else { y = (int)(g.size()); g.push_back({}); cin >> x >> c; --x; z = (int)(c - 'A'); add_edge(x, y, z); add_edge(y, x, z); r.x = x; r.y = y; } } sort(edges.begin(), edges.end()); M = edges.size(); top_links.resize(M);
dsu.resize(g.size()); for (int i = 0; i < (int)g.size(); i++) { dsu[i] = i; }
par.resize(g.size()); par_z.resize(g.size()); d.resize(g.size()); lnks.resize(g.size()); lnks_z.resize(g.size()); lnk_jump.resize(g.size());
bot_links.resize(g.size()); dfs_lnks(0, 0); binary_uplifting(); run_precalc_top(0, 0); run_precalc_bot(0, 0);}
int get_uplift(int x, int k) { for (int p = (int)bu_links.size() - 1; p >= 0; --p) { if (k & (1 << p)) { x = bu_links[p][x]; } } return x;}
int go_up(int x, int &k, const vector<int> &stop_vector) { int p = par[x]; if (x == p) { return x; } int edge_ind = get_edge_ind(x, p), y = 0; for (int _y : stop_vector) { int ny = edges[get_top_link(edge_ind, _y)].second; if (d[y] < d[ny]) { y = ny; } } int dif = d[x] - d[y]; if (k < dif) { y = get_uplift(x, k); k = 0; } else { k -= dif; } return y;}
int go_down(int x, int &k, const vector<int> &stop_vector, const vector<int> &rev_alph) { while (k) { if (lnks[x] == -1) { break; } int y = lnk_jump[x]; for (int _y : stop_vector) { int ny = bot_links[x][_y]; if (d[y] > d[ny]) { y = ny; } } y = get_dsu_parent(y); int dif = d[y] - d[x]; if (k < dif) { y = get_uplift(y, dif - k); k = 0; } else { k -= dif; } if (k) { int ny = -1, nz = 26; for (auto [yy, _zz] : g[y]) { if (yy == par[y] || yy != dsu[yy]) { continue; } int zz = rev_alph[_zz]; if (nz > zz) { nz = zz; ny = yy; } } if (ny == -1) { x = y; break; } --k; y = ny; } x = y; } return x;}
int get_res(int x, int k, const vector<int> &alph) { if (!k) { return x; } vector<int> stop_vector; for (int i = 0; i < (int)alph.size(); i++) { for (int j = i + 1; j < (int)alph.size(); j++) { stop_vector.push_back(pair_map[alph[i]][alph[j]]); } } vector<int> rev_alph(26, -1); for (int i = 0; i < (int)alph.size(); i++) { rev_alph[alph[i]] = i; } if (x != par[x]) { int up_dir = 1; for (auto [y, z] : g[x]) { if (y == par[x] || y != dsu[y]) { continue; } if (rev_alph[par_z[x]] > rev_alph[z]) { up_dir = 0; break; } } if (up_dir) { int pk = k, px = x; x = go_up(x, k, stop_vector); if (k) { int nx = get_uplift(px, pk - k - 1); int y = -1, z = 26; for (auto [ny, _nz] : g[x]) { if (ny == par[x] || ny == nx || ny != dsu[ny]) { continue; } int nz = rev_alph[_nz]; if (nz < z) { y = ny; z = nz; } } if (y == -1) { return x; } x = y; --k; } } } if (k) { x = go_down(x, k, stop_vector, rev_alph); } return x;}
void update_precalc_top(int x) { int p = par[x]; if (x == p || p == par[p]) { return; } int par_edge_ind = get_edge_ind(p, par[p]); int ppz = par_z[p], z = -1; for (auto [y, _z] : g[p]) { if (y != x) { continue; } z = _z; break; } for (auto [y, _z] : g[p]) { if (y == par[p] || y != dsu[y]) { continue; } int edge_ind = get_edge_ind(y, p); int pair_ind = pair_map[z][ppz]; top_links[edge_ind][pair_ind] = get_top_link(par_edge_ind, pair_ind); }}
void solve() { ans.assign(Q, -1); for (int i = Q - 1; i >= 0; --i) { const Req &req = a[i]; if (req.t) { ans[req.ind] = get_res(req.x, req.y, req.alph); } else { dsu[req.y] = get_dsu_parent(par[req.y]); update_precalc_top(req.y); } } for (int i = 0; i < Q; i++) { if (ans[i] != -1) { cout << " " << ans[i] + 1; } } cout << endl;}
int main() { ios_base::sync_with_stdio(false); cin.tie(0); precalc(); int T; cin >> T; for (int t = 1; t <= T; t++) { init(); cout << "Case #" << t << ":"; solve(); } return 0;}123version https://git-lfs.github.com/spec/v1oid sha256:d92c856f4244d69ddbe7faae1fc95df6d99ff46dc684957d4a0ae5140da3b748size 50941290123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172Alphonse is assembling an *alphabet tree* and arranging some adventures along the way.
An alphabet tree is an unrooted tree with \(N\) nodes (numbered from \(1\) to \(N\)) and \(N - 1\) edges. Initially, the \(i\)th edge connects nodes \(A_i\) and \(B_i\) in both directions, and is labeled with a uppercase letter \(C_i\). Two edges incident to a common node are always labeled with different letters.
Alphonse has \(Q\) events to process, the \(i\)th of which is one of two types:
* `1` \(U_i\) \(L_i\): Add a new node to the tree by connecting it to node \(U_i\) with a new edge labeled with uppercase letter \(L_i\). Newly added nodes are numbered with integers starting from \(N + 1\) in the order they're added.* `2` \(U_i\) \(K_i\) \(S_i\): Print the final node Alphonse will end up at if he: - Starts a journey at node \(U_i\). - Repeatedly traverses a previously untraversed edge (on this journey). If his current node has multiple untraversed edges, he picks the edge labeled with the letter that comes earliest in the string \(S_i\). - Ends the journey once there are no more untraversed edges at the current node, or \(K_i\) edges have been traversed on the journey.
Please help Alphonse determine where each journey will take him.
# Constraints
\(1 \le T \le 20\)\(2 \le N \le 300{,}000\)\(1 \le Q \le 300{,}000\)\(1 \le A_i, B_i \le N\)\(A_i \ne B_i\)\(C_i, L_i, S_{i,j} \in \{\)`'A'`, \(\ldots\), `'Z'`\(\}\)\(1 \le U_i, K_i \le 600{,}000\)
The sum of \(N\) over all test cases is at most \(1{,}100{,}000\).The sum of \(Q\) over all test cases is at most \(1{,}100{,}000\).
For each event, it is guaranteed that:- \(U_i\) is a valid node in the tree at the time of the event.- \(L_i\) is different from all existing labels of edges incident to \(U_i\) at the time of the event.- \(S_i\)'s letters are distinct, and are a superset of all edge labels in the tree at the time of the event.
# Input Format
Input begins with a single integer \(T\), the number of test cases. For each test case, there is first a line containing a single integer \(N\). Then, \(N - 1\) lines follow, the \(i\)th of which contains space-separated integers \(A_i\) and \(B_i\), followed by a space, followed by \(C_i\). Then, there is a line containing the single integer \(Q\). Then, \(Q\) lines follow, the \(i\)th of which is either `1` \(U_i\) \(L_i\) or `2` \(U_i\) \(K_i\) \(S_i\).
# Output Format
For the \(i\)th test case, print a single line containing `"Case #i: "`, followed by space-separated integers, the answers to all type-2 events.
# Sample Explanation
{{PHOTO_ID:1175696903384597|WIDTH:550}}
The first sample case's alphabet tree is depicted above, and yields the following journeys:
- Event \(1\) traverses \(1 \stackrel{\texttt{M}}{\longrightarrow} 2 \stackrel{\texttt{E}}{\longrightarrow} 6\) (ended after no more edges from node \(6\))- Event \(2\) traverses \(3 \stackrel{\texttt{E}}{\longrightarrow} 1 \stackrel{\texttt{T}}{\longrightarrow} 4 \stackrel{\texttt{A}}{\longrightarrow} 9\) (ended after \(K_2 = 3\) steps)- Event \(3\) traverses \(9 \stackrel{\texttt{A}}{\longrightarrow} 4 \stackrel{\texttt{T}}{\longrightarrow} 1 \stackrel{\texttt{M}}{\longrightarrow} 2\) (ended after \(K_3 = 3\) steps)- Event \(4\) traverses \(8 \stackrel{\texttt{M}}{\longrightarrow} 3 \stackrel{\texttt{E}}{\longrightarrow} 1 \stackrel{\texttt{T}}{\longrightarrow} 4 \stackrel{\texttt{A}}{\longrightarrow} 9\) (ended after no more edges from node \(9\))- Event \(6\) traverses \(8 \stackrel{\texttt{T}}{\longrightarrow} 10\) (ended after no more edges from node \(10\))
The second and third sample cases are depicted below.
{{PHOTO_ID:1142476319774543|WIDTH:650}}
In the second case, the journeys are:
- Event \(1\) traverses \(1 \stackrel{\texttt{P}}{\longrightarrow} 5 \stackrel{\texttt{C}}{\longrightarrow} 2\) (ended after \(K_1 = 2\) steps)- Event \(2\) traverses \(4 \stackrel{\texttt{P}}{\longrightarrow} 2 \stackrel{\texttt{C}}{\longrightarrow} 5 \stackrel{\texttt{P}}{\longrightarrow} 1\) (ended after \(K_2 = 3\) steps)- Event \(4\) traverses \(4 \stackrel{\texttt{P}}{\longrightarrow} 2 \stackrel{\texttt{C}}{\longrightarrow} 5 \stackrel{\texttt{U}}{\longrightarrow} 6\) (ended after \(K_4 = 3\) steps)- Event \(5\) traverses \(3 \stackrel{\texttt{U}}{\longrightarrow} 2 \stackrel{\texttt{P}}{\longrightarrow} 4\) (ended after no more edges from node \(4\))
In the third case, the journeys are:
- Event \(1\) traverses \(3 \stackrel{\texttt{C}}{\longrightarrow} 2 \stackrel{\texttt{A}}{\longrightarrow} 1\) (ended after \(K_1 = 2\) steps)- Event \(2\) traverses \(4 \stackrel{\texttt{E}}{\longrightarrow} 2 \stackrel{\texttt{A}}{\longrightarrow} 1\) (ended after \(K_2 = 2\) steps)- Event \(3\) traverses \(1 \stackrel{\texttt{A}}{\longrightarrow} 2\) (ended after \(K_3 = 1\) steps)12345678910111213141516171819202122232425The first thing to do is root the tree, for which we can arbitrarily choose node \(1\). Each journey can be done in two phases:1. *Uplifting*: \(k_1\) steps in root's direction (\(k_1\) can be zero).2. *Descent*: \(k_2\) steps in the opposite direction (\(k_2\) can be zero, \(k_1 + k_2 \le K_i\)).
Indeed, after we descend one step, there is no way to start moving up, because the previous edge will always be the edge we need to go upwards (and we can't traverse an edge twice).
Next, notice that adding new nodes don't make the problem significantly harder. We can preprocess all type-1 events and construct the full tree, then process events of both types in reverse order: it's easier to remove nodes rather than to add them. For a reverse type-1 event, we'll replace the node with a reference to its parent so that whenever we get to this node, we instantly return to its parent. For some removals, we must repeat until we reached a node that still exists in the tree. A disjoint set union (DSU) data structure can be used to perform these operations efficiently. For each node, we'll use DSU to find the bottommost ancestor that still exists in the tree.
Now, we'll need a way to perform phase 1 and phase 2 in time faster than \(\mathcal{O}(N + Q)\). For simplicity, we'll describe the solution for an indefinite \(K\). If the destination node is known, we can always backtrack a certain number of steps using binary lifting.
*Phase 1.* In this problem, we have an radix size of \(R = 26\), so we have only \(26 * 25 = 650\) unique pairs of letters. Let's call a pair of letters \((c_1, c_2)\) *active* if \(c_1\) precedes \(c_2\) in the given string \(S_i\). For each edge and pair of letters, we can precompute the ancestor node where the uplifting ends (due to this pair being active) using depth-first search in \(\mathcal{O}((N + Q) * R^2)\). If we start at some node \(v\) and we need to find the node where uplifting stops, we should do the following:
1. Start uplifting at node \(v\). Look through all the edges adjacent to \(v\) to make sure the first edge of the traversal will be the edge to its parent. If not, there is no uplifting for the current event.2. Iterate over all active pairs and pick the bottommost precomputed node across all these pairs for the edge from node \(v\) to its parent. This node is the destination of uplifting.
The total complexity for phase 1 of a single journey is \(\mathcal{O}(R^2)\). We only iterate over at most \(R\) edges and over at most \(R * (R - 1) / 2\) pairs.
*Phase 2.* This phase is slightly more difficult because we have to pick the right edge by ourselves (where in phase 1, we always took the edge from a node to its parent). One possible strategy is to consider the edge that leads to the largest subtree. For each node and pair of letters, we can precompute the descendant node where the descent ends due to this pair being active. The way we use this data is very similar to phase 1:
1. Start the descent at node \(v\).2. Iterate over all active pairs and pick the topmost precomputed node \(u\) across all these pairs for the vertex \(v\). It's possible that \(u = v\).3. Look through all edges adjacent to \(u\) for the next step. If there is no such edge, node \(u\) is the destination of our descent. Otherwise, this edge leads to the node we assign to \(v\), and we return to step 2.
Each time we perform step 3, we reduce the maximum possible number of steps left by at least a half, so at most we will repeat it \(\mathcal{O}(\log(N + Q))\) times for each journey. Since each such step takes \(\mathcal{O}(R^2)\) time, the overall time complexity for phase 2 of a journey is \(\mathcal{O}(\log(N + Q) * R^2)\), and the overall time complexity is therefore \(\mathcal{O}(Q * \log(N + Q) * R^2)\).
12345678910111213141516171819202122232425262728293031323334353637383940414273 1 40 02 24 05 1 40 01 20 34 33 14 1 10 00 11 11 04 3 100 01 910 1010 04 5 100 01 910 1010 07 2 100 010 26 39 65 96 52 87 5 100 010 26 39 65 96 52 8123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397import java.io.PrintWriter;import java.text.DecimalFormat;import java.util.ArrayList;import java.util.Arrays;import java.util.Random;import java.util.Scanner;
public class CupCounterbalancing { static PrintWriter out;
static void solve(Scanner fs, PrintWriter out, int tt) throws InterruptedException { int n = fs.nextInt(), r = fs.nextInt(), max = fs.nextInt(); Vec[] points = new Vec[n]; for (int i = 0; i < n; i++) { points[i] = new Vec(fs.nextInt(), fs.nextInt()); } double ans = solveNaive1e8(points, r, max); out.println("Case #" + tt + ": " + ans); out.flush(); }
static double solveNaive1e8(Vec[] points, int r, int max) { long time = System.currentTimeMillis(); Vec test = new Vec(1, 0).rotate(random.nextDouble()).scale(max / Math.sqrt(1e8)); double res = solveNaive(points, r, max, test); return res; } static double solveNaive1e8Multithreaded( Vec[] points, int r, int max, boolean print, int nThreads) throws InterruptedException { long time = System.currentTimeMillis(); Thread[] threads = new Thread[nThreads]; final double[] answers = new double[nThreads]; for (int i = 0; i < threads.length; i++) { final int ii = i; threads[i] = new Thread(null, null, "T") { public void run() { answers[ii] = solveNaive1e8(points, r, max); } }; threads[i].start(); } for (Thread t : threads) { t.join(); } double average = 0; for (double d : answers) { average += d; } return average / nThreads; }
static Random random = new Random();
static double solveNaive(Vec[] points, int r, int max, Vec test) { test.x = Math.abs(test.x); test.y = Math.abs(test.y); Vec start = new Vec(0, 0); int row = 0; Vec rotated = test.rot90(); Seg[] segs = new Seg[points.length]; for (int i = 0; i < points.length; i++) { segs[i] = new Seg(points[i], points[(i + 1) % points.length]); } int worksCount = 0; int allCount = 0; while (true) { Vec rowStart = start.add(rotated.scale(row)); if (rowStart.y > max) break; Vec at = rowStart; while (at.x <= max && at.y <= max) { if (at.x >= 0 && at.y >= 0) { if (worksNaive(segs, at, r)) { worksCount++; } allCount++; } at = at.add(test); } row++; } row = -1; while (true) { Vec rowStart = start.add(rotated.scale(row)); Vec at = rowStart; boolean hit = false; while (at.x <= max && at.y <= max) { if (at.x >= 0 && at.y >= 0) { hit = true; if (worksNaive(segs, at, r)) { worksCount++; } allCount++; } at = at.add(test); } row--; if (!hit) { break; } } return worksCount / (double) allCount; }
static boolean worksNaive(Seg[] segs, Vec query, long r) { ArrayList<Vec> intersections = new ArrayList<>(); Circle c = new Circle(query, r); for (Seg s : segs) { Vec[] ans = c.intersectSeg(s); if (ans != null) { for (Vec v : ans) { intersections.add(v); } } } double[] angles = new double[intersections.size()]; for (int i = 0; i < angles.length; i++) angles[i] = intersections.get(i).sub(query).angle(); Arrays.sort(angles); if (angles.length <= 2) { return false; } for (int i = 1; i < angles.length; i++) { if (angles[i] - angles[i - 1] >= Math.PI) { return false; } } if (angles[0] - (angles[angles.length - 1] - Math.PI * 2) > Math.PI) { return false; } return true; }
static class Vec { static final double EPS = 1e-6; double x, y; public Vec(double x, double y) { this.x = x; this.y = y; } public Vec add(Vec o) { return new Vec(x + o.x, y + o.y); } public Vec sub(Vec o) { return new Vec(x - o.x, y - o.y); } public Vec scale(double s) { return new Vec(x * s, y * s); } public double dot(Vec o) { return x * o.x + y * o.y; } public double cross(Vec o) { return x * o.y - y * o.x; } public double mag2() { return dot(this); } public double mag() { return Math.sqrt(mag2()); } public Vec unit() { return scale(1 / mag()); } public Vec rot90() { return new Vec(-y, x); } public Vec rot270() { return new Vec(y, -x); }
public Vec rotate(double theta) { double PI = Math.PI; double newX = x * Math.cos(theta) + y * Math.cos(PI / 2 + theta); double newY = x * Math.sin(theta) + y * Math.sin(PI / 2 + theta); return new Vec(newX, newY); }
// Angle between 0 and 2PI public double angle() { return (Math.atan2(y, x) + 2 * Math.PI) % (2 * Math.PI); }
public String toString() { DecimalFormat df = new DecimalFormat("#.##"); return "(" + df.format(x) + ", " + df.format(y) + ")"; }
static boolean eq(double a, double b) { return Math.abs(a - b) < EPS; }
static boolean leq(double a, double b) { return a - EPS < b; } static boolean geq(double a, double b) { return a + EPS > b; }
public boolean equals(Object oo) { Vec o = (Vec) oo; return eq(x, o.x) && eq(y, o.y); } }
static class Seg { Vec from, to, dir;
public Seg(Vec from, Vec to) { this.from = from; this.to = to; dir = to.sub(from); }
// Line-line intersection public Vec lineIntersect(Seg o) { double det = o.dir.x * dir.y - dir.x * o.dir.y; if (Vec.eq(det, 0)) return null; double dist = (o.dir.x * (o.from.y - from.y) - o.dir.y * (o.from.x - from.x)) / det; return from.add(dir.scale(dist)); }
public boolean containsPoint(Vec o) { double distFromLine = dir.unit().cross(o.sub(from)); if (!Vec.eq(distFromLine, 0)) { return false; } return Vec.eq(dir.mag(), from.sub(o).mag() + to.sub(o).mag()); }
// Seg-seg intersection public Vec segIntersection(Seg o) { Vec intersect = lineIntersect(o); if (intersect == null) { return null; } return containsPoint(intersect) && o.containsPoint(intersect) ? intersect : null; }
// Returns 1 if above, 0 if on, -1 if below. public int side(Vec o) { Vec oDir = o.sub(from); double distFromLine = dir.unit().cross(oDir); return Vec.eq(distFromLine, 0) ? 0 : (int)Math.signum(distFromLine); }
public boolean intersects(Seg o) { return side(o.from) != side(o.to) && o.side(from) != o.side(to); }
public Vec getClosestTo(Vec o) { double percentThere = o.sub(from).dot(dir) / dir.mag2(); return from.add(dir.scale(Math.max(0, Math.min(1, percentThere)))); }
public Vec projectToLine(Vec o) { return dir.scale(o.sub(from).dot(dir) / dir.mag2()).add(from); }
// Returns the shortest segment from the x-axis to the point to the y axis. // toContain must be a point with positive x and y coordinates. public static Seg getShortestSegFromAxesContainingQ1Point(Vec toContain) { double slope = -Math.pow(toContain.y / toContain.x, 1.0 / 3); double b = toContain.y - toContain.x * slope; double xInt = -b / slope; return new Seg(new Vec(0, b), new Vec(xInt, 0)); }
public String toString() { return from + " -> " + to; } }
static class Circle { Vec c; double r;
public Circle(Vec c, double r) { this.c = c; this.r = r; }
public boolean contains(Vec v) { return c.sub(v).mag2() - Vec.EPS * Vec.EPS <= r * r; }
// When standing at this circle, returns right tangent, then left tangent. public Vec[] intersect(Circle o) { if (c.equals(o.c)) { return null; } Vec dir = o.c.sub(c); double d2 = dir.mag2(), d = Math.sqrt(d2); if (r + o.r < d || r + d < o.r || o.r + d < r) { return null; } if (Vec.eq(r + o.r, d) || Vec.eq(o.r + d, r)) { return new Vec[] {c.add(dir.scale(r / d))}; } if (Vec.eq(r + d, o.r)) { return new Vec[] {c.sub(dir.scale(r / d))}; } double d1 = (r * r + d2 - o.r * o.r) / (2 * d); double h = Math.sqrt(r * r - d1 * d1); Vec unitDir = dir.unit(); Vec rInt = c.add(unitDir.scale(d1).add(unitDir.rot270().scale(h))); Vec lInt = c.add(unitDir.scale(d1).add(unitDir.rot90().scale(h))); return new Vec[] {rInt, lInt}; }
public double intersectionArea(Circle o) { double d = o.c.sub(c).mag(); if (r + o.r < d) { return 0; } double minR = Math.min(r, o.r), maxR = Math.max(r, o.r), pi = Math.PI; if (Vec.leq(d + minR, maxR)) { return pi * minR * minR; } double theta1 = 2 * Math.acos((r * r + d * d - o.r * o.r) / (2 * r * d)); double theta2 = 2 * Math.acos((o.r * o.r + d * d - r * r) / (2 * o.r * d)); double part1Area = theta1 / 2 * r * r; double part2Area = theta2 / 2 * o.r * o.r; double tri1 = r * r * Math.sin(theta1) / 2; double tri2 = o.r * o.r * Math.sin(theta2) / 2; return part1Area + part2Area - tri1 - tri2; }
// Returns right tangent, then left tangent from perspective of the point public Vec[] getTangentPoints(Vec p) { if (contains(p)) { return null; } double d2 = c.sub(p).mag2(); return new Circle(p, Math.sqrt(d2 - r * r)).intersect(this); }
// Line going from my left to his right, then my right to his left lines go // from me to him public Seg[] internalTangentLines(Circle o) { Vec[] tangentPoints = new Circle(c, r + o.r).getTangentPoints(o.c); Vec offset1 = tangentPoints[0].sub(o.c).rot90().unit().scale(o.r); Vec offset2 = tangentPoints[1].sub(o.c).rot270().unit().scale(o.r); return new Seg[] { new Seg(tangentPoints[0].add(offset1), o.c.add(offset1)), new Seg(tangentPoints[1].add(offset2), o.c.add(offset2)) }; }
// Right external tangent, then left external tangent, from my perspective // lines go from me to him public Seg[] externalTangentLines(Circle o) { if (o.r > r) { Seg[] oAnswer = o.externalTangentLines(this); return new Seg[] { new Seg(oAnswer[1].to, oAnswer[1].from), new Seg(oAnswer[0].to, oAnswer[0].from) }; } Vec[] tangentPoints = new Circle(c, r - o.r).getTangentPoints(o.c); Vec offset1 = tangentPoints[0].sub(o.c).rot270().unit().scale(o.r); Vec offset2 = tangentPoints[1].sub(o.c).rot90().unit().scale(o.r); return new Seg[] { new Seg(tangentPoints[1].add(offset2), o.c.add(offset2)), new Seg(tangentPoints[0].add(offset1), o.c.add(offset1)) }; }
// Line (not line segment)-circle intersection in the order of line.dir public Vec[] intersectLine(Seg line) { Vec closest = line.projectToLine(c); double d2 = closest.sub(c).mag2(); if (d2 > r * r) { return null; } double l = Math.sqrt(r * r - d2); if (Vec.eq(l, 0)) { return new Vec[] {closest}; } Vec lVec = line.dir.unit().scale(l); return new Vec[] {closest.sub(lVec), closest.add(lVec)}; }
// Line segment-circle intersection public Vec[] intersectSeg(Seg seg) { Vec[] lineIntersections = intersectLine(seg); if (lineIntersections == null) return null; ArrayList<Vec> contained = new ArrayList<>(); for (Vec v : lineIntersections) { if (seg.containsPoint(v)) { contained.add(v); } } if (contained.isEmpty()) { return null; } return contained.toArray(new Vec[contained.size()]); }
public String toString() { DecimalFormat df = new DecimalFormat(); return "center: " + c + ", r: " + df.format(r); } }
public static void main(String[] args) throws InterruptedException { Scanner fs = new Scanner(System.in); out = new PrintWriter(System.out); int T = fs.nextInt(); for (int t = 1; t <= T; t++) { solve(fs, out, t); } fs.close(); out.close(); }}12345678910111213141516171819202122232425262728293031323334Courtney has an avant-garde kitchen counter made out of \(N\) rectangular sheets of metal of equal height, standing perpendicular to the ground. When viewed directly from the top, the counter looks like an (unfilled) polygon on a plane with \(N\) edges, the \(i\)th of which extends from point \((X_i, Y_i)\) to point \((X_{(i \text{ mod } N)+1},\, Y_{(i \text{ mod } N)+1})\). These line segments only intersect at their endpoints.
Courtney's friends often make fun of the counter, saying that the thin metal "surface" is useless for holding anything up, but Courtney wants to prove them wrong.
Courtney considers placing a cup with a circular rim of radius \(R\) onto the counter (with the rim facing down), centered at a point chosen uniformly randomly from the square \([0, L] \times [0, L]\). What is the chance that the cup stays balanced on the counter without falling? Your output will be accepted if it is within \(10^{-6}\) of the jury's answer.
*Note: The face-down cup is modeled as an unfilled ring—not as a disk.*
# Constraints
\(1 \le T \le 7\)\(1 \le N \le 7\)\(1 \le R, L \le 15\)\(0 \le X_i, Y_i \le 15\)
# Input Format
Input begins with a single integer \(T\), the number of test cases. For each test case, there is first a line containing three space-separated integers \(N\), \(R\), and \(L\). Then, \(N\) lines follow, the \(i\)th of which contains two space-separated integers \(X_i\) and \(Y_i\),
# Output Format
For the \(i\)th test case, print a line containing `"Case #i: "` followed by a single real number between \(0\) and \(1\), the chance that the cup will balance if placed with its rim centered at a uniformly random point in the square \([0, L] \times [0, L]\).
# Sample Explanation
The counters in the first and second sample cases are depicted below, with the blue regions representing points at which centering the cup will lead to it staying balanced.
{{PHOTO_ID:556593865835592|WIDTH:650}}
1234567Case #1: 0.11696632524550592Case #2: 0.1353446534663839Case #3: 0.0Case #4: 0.020000467220007968Case #5: 0.1027849201777223Case #6: 0.17690065571492997Case #7: 0.03259150141335399123456789101112131415161718Let's call a position where the circle doesn't fall *stable*. First, let's see how we can check whether a given point is stable. Consider all intersection points between that cup and surrounding positions (we can find these naively in linear time). If all of these points lie on a half-circle, then the ring will fall. Otherwise, there will be three points that create a triangle which contains the center of mass of the ring.
**Solution 1:**
As it turns out, any stable point in general form (we can ignore points that are edge cases because those points are ~\(0\%\) of the area) will have at least \(3\) intersections. In fact, if a point is stable it's true that there are a particular \(3\) intersection points that make it stable. This idea is informally supported with what we'll call the "Jenga Principle": if a ring is balancing on \(4\) or more points, one of them will be "loose" in the same way a Jenga block resting on three blocks below it will always be resting on at least one "loose" block which could be removed.
We can case out all of the possible ways that two or three line segments could support a ring, brute force those segments, and then compute the overlap of these shapes. This is tricky to do mathematically for the area on which a ring could balance on two segments (the shapes include more than just circles and line segments), so some method of curve approximation will be useful here.
**Solution 2:**
Actually, if we were to just pick random points \(10^6\) times, we'll get a reasonable approximation of the answer. To get even closer, there are other tricks we can try: first, we can better distribute our points to decrease variance, such as overlaying them evenly in a grid. Once we're there, there are several options to improve our sampling, and we can follow one or more to get a solution which is accurate enough and runs in time:
- Spend less time looking at spaces that are surrounded by points that are either all stable or all unstable: Because the bounds are small, these points are very unlikely to differ from their neighbors once the neighbors are close enough.- Use a *k*-d tree or similar data structure to break up the search space, and stop searching if large areas are \(100\%\) similar after many samples.- Multithread our solution and optimize the constant factor overhead.- Analyze the variance of the solution ahead of time to determine how many samples are needed for a sufficiently accurate estimate.
This optimization can be a tedious but rather straightforward process, and the main challenge is not underestimating the complexity of the potential solutions, or spending too much time on implementation. Notably, the stable region isn't necessarily convex, isn't necessarily entirely located within the polygon, isn't necessarily connected, and can even be connected but with holes.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394#include <bitset>#include <cmath>#include <fstream>#include <iostream>#include <vector>using namespace std;
const int LIM = (int)1e9 + 1;const bool READ_PRIMES_FROM_FILE = true;
vector<int> primes;
void load_primes() { primes.reserve(51000000); if (READ_PRIMES_FROM_FILE) { ifstream fin("primes.txt"); for (int p; fin >> p;) { primes.push_back(p); } } else { bitset<LIM> sieve; int lim = sqrt(LIM); for (int i = 3; i < lim; i += 2) { if (!sieve[i] && i % 2 == 1) { for (int j = i * 2; j < LIM; j += i) { sieve.set(j); } } } primes.push_back(2); for (int i = 3; i <= LIM; i += 2) { if (!sieve[i]) { primes.push_back(i); } } }}
// Returns k in the p^k term of the prime factorization of N!.int legendre_exp(int p, int N) { int ans = 0; for (long long base = p; base <= N; base *= p) { ans += N / base; } return ans;}
int powmod8(int p, int exp) { int ans = 1; for (exp %= 8; exp > 0; exp--) { ans = (ans * p) % 8; } return ans;}
int N, K;
int solve() { bool is_one = true, is_two = true, two_exp_even = false; int mod8prod = 1; for (int p : primes) { if (p > N) { break; } int exp = legendre_exp(p, N) - legendre_exp(p, K); if (exp % 2 != 0) { is_one = false; } if (p % 4 == 3 && exp % 2 == 1) { is_two = false; } if (p == 2 && exp % 2 == 0) { two_exp_even = true; } if (p > 2) { mod8prod = (mod8prod * powmod8(p, exp)) % 8; } } bool is_three = !(two_exp_even && mod8prod == 7); return is_one ? 1 : is_two ? 2 : is_three ? 3 : 4;}
int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); load_primes(); int T; cin >> T; for (int t = 1; t <= T; t++) { cin >> N >> K; cout << "Case #" << t << ": " << solve() << endl; } return 0;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111110
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
2 2
3 2
4 2
5 2
6 2
7 2
8 2
9 2
10 2
3 3
4 3
5 3
6 3
7 3
8 3
9 3
10 3
4 4
5 4
6 4
7 4
8 4
9 4
10 4
5 5
6 5
7 5
8 5
9 5
10 5
6 6
7 6
8 6
9 6
10 6
7 7
8 7
9 7
10 7
8 8
9 8
10 8
9 9
10 9
10 10
28 19
19 16
151 145
100 22
99 22
19348 7362
28365 3726
81727 81723
243447 42273
283738 99824
512556 148938
550385 324141
644639 212476
677786 150413
9876322 738264
1000000000 123456789
75 71
82 79
295 287
17 10
36 22
40 4
63 58
14 6
21 13
26 19
46 16
34 14
77 8
999999992 999999990
999999958 999999956
999999915 999999913
999950885 999950883
999999963 999999960
999999982 999999979
45379 45375
49013 49007
152502 152495
961625 961619
777540 777470
50433 43257
93232 1385
33 31
85 83
285 2831234567891011121314151617181920212223242526272829303132333435363738394041424344454647Ishiko is opening a bracelet shop. Each bracelet she plans to sell is expressed as a ring of \(N\) colored beads, with exactly \(K\) green beads made of emerald, and \(N-K\) remaining beads of all unique colors (neither green nor the same as any other bead in the bracelet). Ishiko has an infinite number of beads available for each of these \(N - K + 1\) different colors.
Ishiko wants to exhibit *one copy of every possible distinct bracelet*. Two bracelets are considered distinct if one is not a cyclic rotation of the other. For instance, the two bracelets on the left are distinct, but the two bracelets on the right are not:
{{PHOTO_ID:876374553707415|WIDTH:700}}
A vendor takes orders for triangular display cases of arbitrary positive integer heights. A case of height \(H\) has \(H\) rows, where the \(i\)th row has \(2*i - 1\) slots, each slot capable of holding one bracelet. For example, a case of height \(3\) is shown below and holds \(1 + 3 + 5 = 9\) bracelets:
{{PHOTO_ID:547949757342773|WIDTH:700}}
How many display cases (of possibly differing heights) will Ishiko need to buy to exhibit one copy of every possible bracelet *without leaving any empty slots in the display cases*?
# Constraints
\(1 \le T \le 110\)\(1 \le N \le 10^9\)\(0 \le K \le N\)
The sum of \(N\) across all test cases is at most \(8{,}000{,}000{,}000\).
# Input Format
Input begins with an integer \(T\), the number of cases. For each case, there is a line containing two space-separated integers, \(N\) and \(K\).
# Output Format
For the \(i\)th case, print `"Case #i: "` followed by a single integer, the minimum number of display cases that Ishiko needs to purchase to exhibit one copy of each bracelet.
# Sample Explanation
In the first sample case, let's say that Ishiko's beads are green, blue, and red. There are \(4\) possible bracelets for \(N = 5\) beads with \(K = 3\) green beads, \(1\) red bead, and \(1\) blue bead (up to rotation):
{{PHOTO_ID:1327255974690671|WIDTH:700}}
Ishiko can use a single display case of height \(2\) to display these \(4\) bracelets.
In the second sample case, let's say that Ishiko's beads are green, blue, red, and yellow. There are \(20\) possible bracelets for \(N = 6\) beads with \(K = 3\) green beads, \(1\) blue bead, \(1\) red bead, and \(1\) yellow bead. Some examples are:
{{PHOTO_ID:853886435922998|WIDTH:700}}
Ishiko can display these bracelets if she purchases a case of height \(2\) and a case of height \(4\).
In the third sample case, there are \(60\) possible bracelets and Ishiko needs at least \(4\) display cases to display all of them. One possibility is that she buys two cases of height \(1\), one case of height \(3\), and one case of height \(7\).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110Case #1: 1Case #2: 1Case #3: 2Case #4: 3Case #5: 3Case #6: 3Case #7: 2Case #8: 3Case #9: 3Case #10: 3Case #11: 1Case #12: 1Case #13: 2Case #14: 3Case #15: 3Case #16: 3Case #17: 2Case #18: 3Case #19: 3Case #20: 3Case #21: 1Case #22: 1Case #23: 3Case #24: 3Case #25: 4Case #26: 2Case #27: 3Case #28: 3Case #29: 3Case #30: 1Case #31: 1Case #32: 1Case #33: 2Case #34: 3Case #35: 3Case #36: 3Case #37: 3Case #38: 1Case #39: 1Case #40: 2Case #41: 3Case #42: 3Case #43: 3Case #44: 3Case #45: 1Case #46: 1Case #47: 3Case #48: 3Case #49: 3Case #50: 3Case #51: 1Case #52: 1Case #53: 4Case #54: 3Case #55: 3Case #56: 1Case #57: 1Case #58: 2Case #59: 2Case #60: 1Case #61: 1Case #62: 1Case #63: 1Case #64: 1Case #65: 1Case #66: 3Case #67: 2Case #68: 2Case #69: 4Case #70: 3Case #71: 3Case #72: 3Case #73: 3Case #74: 4Case #75: 3Case #76: 4Case #77: 4Case #78: 4Case #79: 4Case #80: 3Case #81: 3Case #82: 2Case #83: 2Case #84: 2Case #85: 3Case #86: 3Case #87: 3Case #88: 3Case #89: 4Case #90: 4Case #91: 4Case #92: 4Case #93: 4Case #94: 4Case #95: 4Case #96: 3Case #97: 2Case #98: 1Case #99: 2Case #100: 4Case #101: 2Case #102: 2Case #103: 2Case #104: 4Case #105: 4Case #106: 4Case #107: 4Case #108: 2Case #109: 3Case #110: 4123456789101112131415161718First we need to determine how many bracelets Ishiko is going to exhibit. When \(N = K\) (that is, when all of the beads are green) there is of course just \(1\) bracelet to display. Otherwise, there are \(\frac{(N-1)!}{K!}\) ways to arrange \(N\) beads in a ring when \(K\) are green beads and the rest are unique colors. Since there's always at least \(1\) unique bead, we can say that that unique bead is in a fixed position in each bracelet.
Next, we observe that a display case of height \(H\) holds exactly \(H^2\) bracelets. The problem then is to determine the minimum number of perfect squares needed to sum to \(\frac{(N-1)!}{K!}\). According to [Lagrange's four-square theorem](https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem), we will never need more than \(4\) squares, so Ishiko only needs at most \(4\) display cases.
Let \(X\) be the number of bracelets to be displayed. As \(X\) can be as large as \(1{,}000{,}000{,}000!\), we still need a quick way to determine whether the answer is \(1\), \(2\), \(3\), or \(4\). The answer is \(1\) if \(X\) is a square number, which is something we can determine from the prime factorization of \(X\). If every prime in the factorization appears an even number of times, then \(X\) is a square number.
[Legendre's formula](https://en.wikipedia.org/wiki/Legendre%27s_formula) gives us an easy way to compute the exponent on a given prime \(p\) in the factorization of \(n!\) by summing \(\lfloor n / p^i \rfloor\) for all \(i\), which is quick since \(i\) will never be larger than \(32\) for a \(32\)-bit integer. If \(a\) is the exponent on \(p\) in \(N-1!\), and \(b\) is the exponent on \(p\) in \(K\), then the exponent on \(p\) in \(\frac{(N-1!)}{K!}\) is just \(a - b\).
How can we tell if the answer is \(2\)? Why, we can just apply the aptly-named [two-square theorem](https://en.wikipedia.org/wiki/Sum_of_two_squares_theorem), which says that \(X\) can be represented as a sum of two squares if and only if its prime decomposition contains no factor \(p^k\), where \(p \equiv 3\ (\text{mod}\ 4)\) and \(k\) is odd. Since we already have the prime factorization of \(X\), this is easy to determine.
To determine if the answer is \(3\), we'll appeal to Legendre once more. [Legendre's three-square theorem](https://en.wikipedia.org/wiki/Legendre%27s_three-square_theorem) says that \(X\) can be represented as a sum of three squares as long as it is *not* of the form \(X = 4^a(8b + 7)\), for non-negative \(a\) and \(b\). We can check if \(X\) has a factor of \(4\) by checking if the exponent on \(2\) in the prime factorization is even. If so, we can then check if \(X / 4^a \equiv 7\ (\text{mod}\ 8)\) by multiplying all prime factors higher than \(2\), modulo \(8\). Once again, \(X\) can't have more than \(32\) distinct factors as \(N\) and \(K\) are both \(32\)-bit integers, so this computation is also quick.
In the end, if the answer isn't \(1\), \(2\), or \(3\), then it must be \(4\).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356#include <algorithm>#include <iostream>#include <memory>#include <unordered_map>#include <unordered_set>#include <vector>using namespace std;
using int64 = long long;
const int MAX_COORD = 300000;
struct Rect { int x1, y1, x2, y2, id; int mappedX1, mappedY1, mappedX2, mappedY2; bool ends_alive;
Rect() {} Rect(int _x1, int _y1, int _x2, int _y2, int _id) : x1(_x1), y1(_y1), x2(_x2), y2(_y2), id(_id) {}
bool intersects(const Rect &o) const { return x2 >= o.x1 && x1 <= o.x2 && y1 <= o.y2 && y2 >= o.y1; }
void merge_in(const Rect &o) { x1 = min(x1, o.x1); mappedX1 = min(mappedX1, o.mappedX1); y1 = min(y1, o.y1); mappedY1 = min(mappedY1, o.mappedY1); x2 = max(x2, o.x2); mappedX2 = max(mappedX2, o.mappedX2); y2 = max(y2, o.y2); mappedY2 = max(mappedY2, o.mappedY2); }
bool operator <(const Rect &o) { return id < o.id; }};
class InnerST { int lo, hi, delta; unique_ptr<InnerST> lchild, rchild;
void init_children() { if (!lchild) { int mid = lo + (hi - lo) / 2; lchild = make_unique<InnerST>(lo, mid); rchild = make_unique<InnerST>(mid + 1, hi); } }
public: InnerST(int l, int h) : lo(l), hi(h), delta(0), lchild(nullptr), rchild(nullptr) {}
void add(int l, int h, int d) { if (l > hi || h < lo) { return; } if (l <= lo && h >= hi) { delta += d; return; } init_children(); lchild->add(l, h, d); rchild->add(l, h, d); }
int query(int at) { if (lo == hi || !lchild) { return delta; } init_children(); return delta + (at <= lchild->hi ? lchild : rchild)->query(at); }};
class OuterST { int lo, hi, inner_lo, inner_hi; unique_ptr<OuterST> lchild, rchild; InnerST inner;
public: OuterST(int l, int h, int inner_l, int inner_h) : lo(l), hi(h), inner_lo(inner_l), inner_hi(inner_h), inner(inner_l, inner_h) { if (lo != hi) { int mid = lo + (hi - lo) / 2; lchild = make_unique<OuterST>(lo, mid, inner_lo, inner_hi); rchild = make_unique<OuterST>(mid + 1, hi, inner_lo, inner_hi); } }
// Adds a line to the inner dimension spanning inner_lo to inner_hi on // outer_idx void add_inner(int64 outer_idx, int inner_lo, int inner_hi) { inner.add(inner_lo, inner_hi, 1); if (lo != hi) { if (outer_idx <= lchild->hi) { lchild->add_inner(outer_idx, inner_lo, inner_hi); } else { rchild->add_inner(outer_idx, inner_lo, inner_hi); } } }
// Queries all y's that have something here. vector<int> query_inner(int outer_lo, int outer_hi, int inner_idx) { if (outer_lo > hi || outer_hi < lo || inner.query(inner_idx) == 0) return {}; if (lo == hi) { return {lo}; } auto lres = lchild->query_inner(outer_lo, outer_hi, inner_idx); auto rres = rchild->query_inner(outer_lo, outer_hi, inner_idx); vector<int> sum(lres.size() + rres.size()); for (int i = 0; i < (int)sum.size(); i++) { sum[i] = i < (int)lres.size() ? lres[i] : rres[i - lres.size()]; } return sum; }
void remove_inner(int outer_idx, int inner_lo, int inner_hi) { inner.add(inner_lo, inner_hi, -1); if (lo != hi) { if (outer_idx <= lchild->hi) { lchild->remove_inner(outer_idx, inner_lo, inner_hi); } else { rchild->remove_inner(outer_idx, inner_lo, inner_hi); } } }};
class RectHolder { struct RectMapping { int value; Rect *r; bool v1;
bool operator<(const RectMapping &r) const { return value < r.value; } };
int sz; vector<int64> mapsXMajor, mapsYMajor; unordered_set<Rect*> aliveRects; OuterST xMajorST, yMajorST; vector<Rect*> usingXMapping, usingYMapping; vector<int> firstOfXMajor, lastOfXMajor; vector<int> firstOfYMajor, lastOfYMajor;
public: RectHolder(vector<Rect> &rects) : sz(rects.size()), xMajorST(0, 2 * sz, 0, 2 * sz), yMajorST(0, 2 * sz, 0, 2 * sz), usingXMapping(2 * sz), usingYMapping(2 * sz), firstOfXMajor(2 * sz, (int)1e9), lastOfXMajor(2 * sz, -1), firstOfYMajor(2 * sz, (int)1e9), lastOfYMajor(2 * sz, -1) { vector<RectMapping> xMappings(2 * sz), yMappings(2 * sz); for (int i = 0; i < sz; i++) { xMappings[i * 2] = (RectMapping){rects[i].x1, &rects[i], true}; xMappings[i * 2 + 1] = (RectMapping){rects[i].x2, &rects[i], false}; yMappings[i * 2] = (RectMapping){rects[i].y1, &rects[i], true}; yMappings[i * 2 + 1] = (RectMapping){rects[i].y2, &rects[i], false}; } sort(xMappings.begin(), xMappings.end()); sort(yMappings.begin(), yMappings.end()); for (int i = 0; i < (int)xMappings.size(); i++) { usingXMapping[i] = xMappings[i].r; usingYMapping[i] = yMappings[i].r; if (xMappings[i].v1) { xMappings[i].r->mappedX1 = i; int orig = xMappings[i].r->x1; firstOfXMajor[orig] = min(firstOfXMajor[orig], i); lastOfXMajor[orig] = max(lastOfXMajor[orig], i); } else { xMappings[i].r->mappedX2 = i; int orig = xMappings[i].r->x2; firstOfXMajor[orig] = min(firstOfXMajor[orig], i); lastOfXMajor[orig] = max(lastOfXMajor[orig], i); } if (yMappings[i].v1) { yMappings[i].r->mappedY1 = i; int orig = yMappings[i].r->y1; firstOfYMajor[orig] = min(firstOfYMajor[orig], i); lastOfYMajor[orig] = max(lastOfYMajor[orig], i); } else { yMappings[i].r->mappedY2 = i; int orig = yMappings[i].r->y2; firstOfYMajor[orig] = min(firstOfYMajor[orig], i); lastOfYMajor[orig] = max(lastOfYMajor[orig], i); } } }
void add_rect(Rect *r) { aliveRects.insert(r); usingXMapping[r->mappedX1] = r; usingXMapping[r->mappedX2] = r; usingYMapping[r->mappedY1] = r; usingYMapping[r->mappedY2] = r; xMajorST.add_inner(r->mappedX1, r->y1, r->y2); yMajorST.add_inner(r->mappedY1, r->x1, r->x2); xMajorST.add_inner(r->mappedX2, r->y1, r->y2); yMajorST.add_inner(r->mappedY2, r->x1, r->x2); }
void remove_rect(Rect *r) { aliveRects.erase(r); xMajorST.remove_inner(r->mappedX1, r->y1, r->y2); yMajorST.remove_inner(r->mappedY1, r->x1, r->x2); xMajorST.remove_inner(r->mappedX2, r->y1, r->y2); yMajorST.remove_inner(r->mappedY2, r->x1, r->x2); }
unordered_set<Rect*> get_alive_rect_intersecting(Rect *r) { unordered_set<Rect*> res; auto xsToTake1 = xMajorST.query_inner(firstOfXMajor[r->x1], lastOfXMajor[r->x2], r->y1); auto xsToTake2 = xMajorST.query_inner(firstOfXMajor[r->x1], lastOfXMajor[r->x2], r->y2); auto ysToTake1 = yMajorST.query_inner(firstOfYMajor[r->y1], lastOfYMajor[r->y2], r->x1); auto ysToTake2 = yMajorST.query_inner(firstOfYMajor[r->y1], lastOfYMajor[r->y2], r->x2); for (int x : xsToTake1) res.insert(usingXMapping[x]); for (int x : xsToTake2) res.insert(usingXMapping[x]); for (int y : ysToTake1) res.insert(usingYMapping[y]); for (int y : ysToTake2) res.insert(usingYMapping[y]); return res; }
unordered_set<Rect*> get_all_alive_rects() { return aliveRects; }};
struct Event { int x, y1, y2; bool adding; Rect *r;
bool operator<(const Event &e) const { if (x != e.x) { return x < e.x; } return (y2 - y1) < (e.y2 - e.y1); }};
int64 solve() { int N; vector<Rect> rects; vector<int> xvals, yvals; unordered_map<int, int> x_map, y_map, x_rev, y_rev; // Input. cin >> N; for (int i = 0, x, y; i < N; i++) { cin >> x >> y; rects.push_back(Rect(x - 1, y - 1, x + 1, y + 1, i)); xvals.push_back(x - 1); xvals.push_back(x + 1); yvals.push_back(y - 1); yvals.push_back(y + 1); } // Compress rectangles. sort(xvals.begin(), xvals.end()); xvals.resize(distance(xvals.begin(), unique(xvals.begin(), xvals.end()))); sort(yvals.begin(), yvals.end()); yvals.resize(distance(yvals.begin(), unique(yvals.begin(), yvals.end()))); int i = 0; for (int x : xvals) { x_rev[i] = x; x_map[x] = i++; } i = 0; for (int y : yvals) { y_rev[i] = y; y_map[y] = i++; } for (Rect &r : rects) { r.x1 = x_map[r.x1]; r.y1 = y_map[r.y1]; r.x2 = x_map[r.x2]; r.y2 = y_map[r.y2]; } // Add to rect holder. RectHolder holder(rects); for (Rect &to_add : rects) { while (true) { auto kill_now = holder.get_alive_rect_intersecting(&to_add); if (kill_now.empty()) { break; } for (Rect *to_kill : kill_now) { holder.remove_rect(to_kill); to_add.merge_in(*to_kill); } } holder.add_rect(&to_add); } // Line sweep to remove any rectangles that are inside another rectangle sweep // left to right. On an X, process bigger then smaller. auto alive = holder.get_all_alive_rects(); InnerST st(0, MAX_COORD); vector<Event> events; for (Rect *r : alive) { r->ends_alive = true; events.push_back((Event){r->x1, r->y1, r->y2, true, r}); events.push_back((Event){r->x2, r->y1, r->y2, false, r}); } sort(events.begin(), events.end()); for (Event &e : events) { if (e.adding) { if (st.query(e.y1) == 0) { st.add(e.y1, e.y2, 1); } else { e.r->ends_alive = false; } } else { if (e.r->ends_alive) { st.add(e.y1, e.y2, -1); } } } // Uncompress and calculate areas. int64 ans = 0; for (const Rect &r : rects) { if (r.ends_alive) { int x1 = x_rev[r.x1], x2 = x_rev[r.x2]; int y1 = y_rev[r.y1], y2 = y_rev[r.y2]; ans += (int64)(x2 - x1) * (y2 - y1); } } return ans;}
int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; for (int t = 1; t <= T; t++) { cout << "Case #" << t << ": " << solve() << endl; } return 0;}123version https://git-lfs.github.com/spec/v1oid sha256:c3e8c58a3c7758bc0da422772c427080af5d6dc0b55036481e1a6e34cbe13e73size 459466331234567891011121314151617181920212223242526272829303132333435363738394041Boss Rob planted \(N\) happy little hazel trees in his yard (represented on a Cartesian plane). The \(i\)th tree is at integer coordinates \((X_i, Y_i)\). It's harvesting season, and Rob would like to set up some nets around the trees to collect the hazelnuts that fall.
Each net must be an axis-aligned rectangle with integer vertices (on lattice points). Rob needs at least \(1\) unit of space between nets so he can walk between them and collect the nuts. That is, nets cannot intersect, touch, or be nested. Each tree must lie strictly inside its net, i.e. must be at least \(1\) unit away from the net's edge.
Boss Rob can set up any number of nets, but would like to know the minimum total area of net required to cover all \(N\) trees.
# Constraints
\(1 \le T \le 160\)\(1 \le N \le 800{,}000\)\(0 \le X_i, Y_i \le 10^9\)All \((X_i, Y_i)\) in a given test case are distinct.
\(N > 500{,}000\) in at most two test cases.The sum of \(N\) over all test cases is at most \(4{,}000{,}000\).
# Input Format
Input begins with an integer \(T\), the number of cases. For each case, there is first a line containing a single integer \(N\). Then, \(N\) lines follow, the \(i\)th of which contains two space-separated integers \(X_i\) and \(Y_i\).
# Output Format
For the \(i\)th case, print a line containing `"Case #i: "` followed by a single integer, the minimum total area of net needed to enclose all trees according to the above requirements.
# Sample Explanation
Solutions for the first two sample cases are depicted below.
{{PHOTO_ID:2468652649959145|WIDTH:700}}
In the first case, the minimum possible net area is \(2*2 + 3*4 + 2*2 = 20\).
In the second case, the minimum possible net area is \(2*2 + 4*6 = 28\).
In the third case, it's almost possible to give each tree its own net. Unfortunately, there needs to be at least \(1\) unit of space between the nets at \((2, 2)\) so Boss Rob can walk through. This makes it indirectly necessary to use one big net to cover all trees.
{{PHOTO_ID:504150738360453|WIDTH:700}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160Case #1: 20Case #2: 28Case #3: 42Case #4: 135Case #5: 139Case #6: 136Case #7: 82Case #8: 93Case #9: 170Case #10: 194Case #11: 163Case #12: 109Case #13: 85Case #14: 1000002Case #15: 250001000001Case #16: 1000002Case #17: 2560000000000Case #18: 1920000000000Case #19: 8778Case #20: 2643382Case #21: 56Case #22: 38Case #23: 34Case #24: 36Case #25: 33Case #26: 81Case #27: 56Case #28: 40Case #29: 42Case #30: 34Case #31: 49Case #32: 81Case #33: 60Case #34: 56Case #35: 36Case #36: 46Case #37: 26Case #38: 38Case #39: 30Case #40: 63Case #41: 21Case #42: 22Case #43: 25Case #44: 24Case #45: 24Case #46: 16Case #47: 25Case #48: 30Case #49: 20Case #50: 30Case #51: 20Case #52: 20Case #53: 25Case #54: 20Case #55: 14Case #56: 30Case #57: 16Case #58: 30Case #59: 20Case #60: 30Case #61: 64Case #62: 45Case #63: 72Case #64: 72Case #65: 72Case #66: 54Case #67: 72Case #68: 72Case #69: 72Case #70: 43Case #71: 54Case #72: 36Case #73: 56Case #74: 63Case #75: 72Case #76: 46Case #77: 64Case #78: 48Case #79: 81Case #80: 49Case #81: 42Case #82: 72Case #83: 39Case #84: 52Case #85: 58Case #86: 72Case #87: 64Case #88: 50Case #89: 81Case #90: 58Case #91: 28Case #92: 72Case #93: 81Case #94: 58Case #95: 72Case #96: 72Case #97: 72Case #98: 38Case #99: 52Case #100: 48Case #101: 81Case #102: 56Case #103: 37Case #104: 72Case #105: 64Case #106: 72Case #107: 62Case #108: 54Case #109: 58Case #110: 64Case #111: 52Case #112: 45Case #113: 72Case #114: 44Case #115: 72Case #116: 49Case #117: 81Case #118: 37Case #119: 38Case #120: 40Case #121: 63Case #122: 32Case #123: 56Case #124: 72Case #125: 64Case #126: 72Case #127: 63Case #128: 48Case #129: 72Case #130: 49Case #131: 42Case #132: 42Case #133: 37Case #134: 81Case #135: 81Case #136: 63Case #137: 56Case #138: 72Case #139: 81Case #140: 63Case #141: 33Case #142: 56Case #143: 40Case #144: 81Case #145: 61Case #146: 49Case #147: 48Case #148: 63Case #149: 64Case #150: 54Case #151: 81Case #152: 56Case #153: 56Case #154: 63Case #155: 34Case #156: 56Case #157: 72Case #158: 72Case #159: 72Case #160: 72123456789101112131415161718192021First, we'll note a greedy philosophy that if we can simply use a \(2 \times 2\) square around all trees, that’d be the best solution possible. If not, the only reason why is that some pair of these squares intersects and so we are forced to union them. It turns out there is therefore no decision making that needs to happen here; we simply must find an efficient way of simulating the unions and discovering overlapping pairs.
We can maintain a set of our current answer (the answer for some prefix), and consider the next rectangle one by one. To add rectangle \(R\) (it'll initially be a \(2 \times 2\) square, but may grow), first find all rectangles that intersect \(R\). Expand \(R\)'s boundaries to include them, and then remove them from our set, and repeat. Once we find no intersections for our expanded \(R\), add it to the set, and consider the next \(2 \times 2\) square.
To do this fast, we'll need a data structure to do the following:
- Add one rectangle to the set in \(\mathcal{O}(\log^2 N)\) time- Remove one rectangle from the set in \(\mathcal{O}(\log^2 N)\) time- Get all rectangles whose outline intersects a query rectangle \(R\). If there are \(s\) of these, our time complexity should be at most \(\mathcal{O}(s*\log^2 N)\). This running time is affordable because any rectangle returned here will immediately be removed, so this cost can be conceptually ignored and amortized into that subsequent removal cost.
To implement this, we'll build a helper structure: a segment tree that holds all vertical lines. It will be able to query all of the \(x\) coordinates of vertical lines that intersect a given horizontal line.
The structure consists of an outer segment tree over all \(x\)'s. For a node \(n\) in the outer segment tree which is responsible for \(x\)'s in the range \([l..r]\), node \(n\) will store an implicit segment tree that can tell us all of the \(y\)'s for which there is a vertical line with an \(x\) coordinate in \([l..r]\). To answer a query for all intersecting segments in range \([l..r]\), we can walk the outer segment tree, only going down a layer if the implicit segment tree at some node tells us that we’ll find an intersecting segment by going down that path. We can make implementation a bit faster by giving a unique ID to each rectangle’s initial borders. That way we can guarantee there’s at most one rectangle with a vertical line at any particular \(x\).
This segment tree lets us add vertical lines and query horizontal ones, so we’ll create another copy of it of add horizontal lines and query vertical ones.
Using the above operations, we can repeatedly add a rectangle and union it with any rectangles which intersect *at a border*. However, there’s still one case this doesn’t catch: it’s possible that one rectangle grows quite large and then *contains* another smaller rectangle. To handle this, we can do a simple line sweep at the end to catch any rectangles that are completely inside another. Specifically, we can sweep across \(x\)'s with an event for each rectangle’s left side (start event) and right side (end event) and maintain a segment tree of which \(y\)'s are inside a rectangle. At a start event, if we’re inside a larger rectangle, then we can mark the inner rectangle as "dead" and not add its area to the answer.
This gives us a final solution that runs in \(O(N*\log^2 N)\) time and is fast enough to solve all cases even in Java.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102#include <algorithm>#include <cmath>#include <iostream>#include <tuple>#include <vector>using namespace std;
const int SAMPLES = 500;const int BOUNDS = 50;
int N;vector<pair<double, double>> P;
inline double distsq(double dx, double dy) { return dx * dx + dy * dy; }
bool check(int x, int y, int r) { double Rsq = r*r; for (int i = 0; i < min(N, SAMPLES); i++) { if (distsq(x - P[i].first, y - P[i].second) > Rsq) { return false; } } return true;}
void solve() { cin >> N; P.resize(N); for (int i = 0; i < N; i++) { cin >> P[i].first >> P[i].second; } // Generate valid circles. vector<tuple<int, int, int>> circles; for (int Ax = 0; Ax <= BOUNDS; Ax++) { for (int Ay = 0; Ay <= BOUNDS; Ay++) { int Ar = 1; while (Ar <= BOUNDS && !check(Ax, Ay, Ar)) { Ar++; } if (Ar <= BOUNDS) { circles.push_back({Ax, Ay, Ar}); } } } // Try for all valid circles. int bestAx = -1, bestAy = -1, bestBx = -1, bestBy = -1, bestR = -1; double bestArea = 999999; for (int a = 0; a < (int)circles.size(); a++) { auto [Ax, Ay, R] = circles[a]; for (int b = a + 1; b < (int)circles.size(); b++) { auto [Bx, By, Br] = circles[b]; if (R != Br) { continue; } double dsq = distsq(Ax - Bx, Ay - By); // Fail if circles don't overlap. if (dsq >= 4 * R * R) { continue; } // Choose the answer that minimizes the area of the overlap. double d = sqrt(dsq); double fouradsq = sqrt((4 * R * R) - dsq); double area = R * R * M_PI; area -= 2 * R * R * atan2(d, fouradsq); area -= 0.5 * d * fouradsq; if (area < bestArea) { bestArea = area; bestAx = Ax; bestAy = Ay; bestBx = Bx; bestBy = By; bestR = R; } } } // Compute sum of squared distance to points from both A and B. // If B's sum is less, B is actually A. // Note: We can afford to use all N points for this, no need to sample. double Asum = 0, Bsum = 0; for (auto [x, y] : P) { Asum += distsq(x - bestAx, y - bestAy); Bsum += distsq(x - bestBx, y - bestBy); } if (Bsum < Asum) { swap(bestAx, bestBx); swap(bestAy, bestBy); } cout << bestAx << " " << bestAy << " " << bestBx << " " << bestBy << " " << bestR << endl;}
int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; for (int t = 1; t <= T; t++) { cout << "Case #" << t << ": "; solve(); } return 0;}123version https://git-lfs.github.com/spec/v1oid sha256:9793101756bfe31462ebbc8c026f5f60eb5ca5346502ea92faf895d3e04f3274size 39285035123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051You just landed a job as a machine learning engineer! As a ramp-up exercise, Boss Rob tasked you with modeling the watering wells in his yard, which can be represented on a Cartesian plane.
Boss Rob has a primary well at point \((A_x, A_y)\) and a backup well at a different point \((B_x, B_y)\), each able to water trees within an \(R\) unit radius. Using \(A_x\), \(A_y\), \(B_x\), \(B_y\), and \(R\) (unknown integers to you), Rob plants \(N\) happy little trees at real number points obtained by \(N\) calls to the function:
```def gen_one_tree(A_x, A_y, B_x, B_y, R): while True: r = random.uniform(0, R) theta = random.uniform(0, 2*math.pi) x = A_x + r*math.cos(theta) y = A_y + r*math.sin(theta) if (x - B_x)**2 + (y - B_y)**2 <= R*R: return (x, y)```Here, `random.uniform(L, H)` returns a real number in \([L, H)\) uniformly at random.
In other words, he picks a point \((x, y)\) in the circular range of the primary well using the special method above. If \((x, y)\) happens to be in range of the backup well, he plants a tree there (else he discards it and tries again with a new \((x, y)\)). This repeats until Rob has planted \(N\) trees.
Given only the planted tree coordinates \((X_1, Y_1), \ldots, (X_N, Y_N)\), you are tasked to predict the exact values of \(A_x\), \(A_y\), \(B_x\), \(B_y\), and \(R\). As you are new, Boss Rob will accept your solution if it correctly predicts at least \(80\%\) of the test cases.
# Constraints
\(1 \le T \le 1{,}000\)\(500 \le N \le 1{,}000{,}000\)\(0 \le A_x, A_y, B_x, B_y \le 50\)\((A_x, A_y) \ne (B_x, B_y)\)\(1 \le R \le 50\)The sum of \(N\) across all test cases is at most \(2{,}000{,}000\).
The intersection area of the two circular regions is strictly positive.
Tree coordinates in the data were truly generated using the randomized algorithm as described above. The secret parameters \(A_x\), \(A_y\), \(B_x\), \(B_y\), and \(R\) have also been chosen uniformly at random for each case (rejecting cases where the circles are identical or do not have positive overlap).
# Input Format
Input begins with a single integer \(T\), the number of test cases. For each case, there is first a line containing a single integer \(N\), the number of planted trees. Then, \(N\) lines follow, the \(i\)th of which contains two space-separated real numbers \(X_i\) and \(Y_i\), each given to \(6\) decimal places.
# Output Format
For the \(i\)th test case, print a line containing `"Case #i: "`, followed by the five space-separated integers \(A_x\), \(A_y\), \(B_x\), \(B_y\), and \(R\), in that order.
# Sample Explanation
The first sample case is pictured below, with the primary well's range in red, the backup well's range in blue, and the \(500\) randomly-generated trees in green:
{{PHOTO_ID:6502772429739994|WIDTH:700}}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000Case #1: 30 35 31 14 46Case #2: 46 11 39 5 46Case #3: 18 26 20 16 35Case #4: 15 45 1 1 43Case #5: 37 48 46 27 21Case #6: 14 31 49 30 35Case #7: 27 39 14 36 11Case #8: 32 40 16 50 28Case #9: 16 12 26 14 12Case #10: 50 11 48 24 48Case #11: 21 14 17 39 24Case #12: 22 12 49 24 30Case #13: 30 10 1 43 29Case #14: 33 28 38 10 40Case #15: 30 8 21 31 18Case #16: 38 34 32 25 23Case #17: 24 44 46 29 43Case #18: 4 1 42 11 22Case #19: 6 40 23 3 36Case #20: 49 17 9 6 26Case #21: 34 17 36 5 45Case #22: 15 21 20 38 12Case #23: 0 35 34 28 23Case #24: 7 25 40 8 46Case #25: 11 43 40 6 48Case #26: 2 44 50 28 30Case #27: 19 18 20 17 28Case #28: 18 33 26 27 24Case #29: 37 13 6 16 42Case #30: 16 2 28 12 43Case #31: 25 44 11 48 18Case #32: 39 21 46 11 18Case #33: 14 18 11 29 11Case #34: 35 0 42 5 22Case #35: 45 24 47 11 26Case #36: 22 26 30 31 5Case #37: 44 6 24 8 27Case #38: 17 30 16 29 38Case #39: 45 49 21 23 26Case #40: 43 7 9 0 29Case #41: 10 12 8 46 34Case #42: 29 33 21 15 28Case #43: 10 2 29 49 45Case #44: 12 36 49 48 37Case #45: 47 40 12 16 48Case #46: 41 26 20 48 23Case #47: 36 25 15 15 26Case #48: 36 15 28 43 18Case #49: 28 42 37 4 29Case #50: 41 6 40 43 32Case #51: 33 33 25 9 37Case #52: 33 30 28 9 32Case #53: 47 11 33 24 11Case #54: 25 45 11 46 25Case #55: 16 15 2 49 38Case #56: 42 35 2 43 22Case #57: 12 0 26 7 26Case #58: 24 36 27 4 27Case #59: 34 44 33 37 19Case #60: 48 34 13 44 48Case #61: 38 28 50 44 15Case #62: 50 36 38 50 29Case #63: 18 31 41 30 37Case #64: 22 0 38 25 22Case #65: 47 48 34 20 45Case #66: 35 49 24 42 21Case #67: 27 40 39 25 46Case #68: 17 1 20 15 28Case #69: 2 20 41 46 45Case #70: 23 30 24 23 4Case #71: 37 36 4 11 39Case #72: 37 44 28 44 39Case #73: 26 19 4 36 40Case #74: 40 43 48 41 37Case #75: 9 35 26 43 35Case #76: 8 4 44 29 23Case #77: 15 5 22 34 20Case #78: 2 24 33 26 47Case #79: 6 45 27 6 47Case #80: 47 40 24 6 24Case #81: 46 5 41 41 23Case #82: 8 14 38 1 25Case #83: 26 50 21 39 30Case #84: 49 44 0 1 49Case #85: 19 32 40 48 25Case #86: 35 22 42 21 30Case #87: 50 17 3 18 44Case #88: 45 43 23 11 43Case #89: 0 39 0 15 35Case #90: 8 15 32 46 38Case #91: 15 2 47 35 38Case #92: 10 9 26 12 16Case #93: 21 15 15 15 45Case #94: 50 41 4 12 38Case #95: 21 41 44 50 50Case #96: 33 32 47 17 23Case #97: 32 20 28 10 7Case #98: 35 49 45 24 37Case #99: 24 26 45 48 33Case #100: 23 13 34 40 39Case #101: 40 20 27 7 21Case #102: 0 33 1 8 33Case #103: 30 16 19 26 27Case #104: 22 49 49 42 47Case #105: 9 40 13 5 26Case #106: 16 26 12 8 36Case #107: 12 12 7 45 44Case #108: 26 50 13 21 41Case #109: 9 38 39 1 47Case #110: 14 6 32 40 34Case #111: 34 45 25 14 44Case #112: 28 35 46 42 21Case #113: 25 23 2 23 45Case #114: 29 38 14 42 12Case #115: 25 25 20 8 33Case #116: 16 39 47 1 41Case #117: 44 16 29 32 29Case #118: 30 5 46 19 28Case #119: 48 13 17 28 35Case #120: 35 15 5 1 24Case #121: 19 18 31 31 32Case #122: 35 11 14 23 36Case #123: 45 24 20 49 21Case #124: 20 41 38 50 16Case #125: 22 11 16 40 18Case #126: 48 46 26 43 50Case #127: 28 11 36 13 40Case #128: 12 50 1 48 22Case #129: 15 34 19 5 40Case #130: 32 36 9 27 44Case #131: 5 48 43 14 50Case #132: 15 32 44 22 36Case #133: 8 42 12 40 24Case #134: 38 7 50 0 47Case #135: 21 15 25 12 43Case #136: 43 35 45 4 41Case #137: 38 24 29 3 14Case #138: 1 26 4 4 35Case #139: 7 50 27 45 11Case #140: 45 33 46 16 19Case #141: 45 38 37 44 37Case #142: 12 32 38 40 34Case #143: 33 1 29 30 50Case #144: 26 27 50 31 22Case #145: 3 0 25 16 18Case #146: 25 17 2 34 18Case #147: 30 20 33 20 40Case #148: 6 34 17 30 26Case #149: 30 10 3 20 28Case #150: 2 15 33 6 26Case #151: 8 43 13 42 26Case #152: 14 44 3 48 26Case #153: 42 50 41 24 31Case #154: 28 11 37 46 38Case #155: 6 4 39 16 50Case #156: 28 12 35 46 21Case #157: 50 37 14 28 39Case #158: 10 24 6 9 46Case #159: 0 18 9 32 35Case #160: 17 38 15 37 24Case #161: 48 41 10 0 29Case #162: 37 6 11 14 32Case #163: 50 47 30 47 34Case #164: 25 42 26 4 33Case #165: 10 16 17 19 20Case #166: 46 16 9 10 27Case #167: 20 44 38 23 26Case #168: 4 41 48 43 39Case #169: 28 44 17 47 9Case #170: 39 25 4 46 33Case #171: 1 15 38 7 21Case #172: 8 25 41 47 25Case #173: 3 9 32 3 45Case #174: 36 4 24 29 30Case #175: 10 39 21 39 38Case #176: 8 42 18 49 46Case #177: 13 48 27 32 35Case #178: 19 4 18 23 31Case #179: 1 40 29 48 17Case #180: 31 21 31 48 18Case #181: 17 24 40 15 35Case #182: 2 8 28 2 45Case #183: 5 15 35 33 26Case #184: 27 21 26 0 36Case #185: 14 39 28 39 33Case #186: 23 14 11 22 46Case #187: 48 47 1 28 34Case #188: 34 47 12 16 33Case #189: 22 47 24 39 45Case #190: 20 9 13 21 48Case #191: 6 49 27 39 50Case #192: 38 4 25 16 21Case #193: 25 0 4 17 47Case #194: 19 4 42 11 32Case #195: 50 47 32 31 32Case #196: 30 36 12 1 25Case #197: 40 40 34 41 40Case #198: 4 45 50 38 49Case #199: 42 39 50 39 8Case #200: 19 38 35 19 40Case #201: 49 3 15 18 44Case #202: 35 42 35 38 31Case #203: 29 50 40 4 47Case #204: 22 37 33 46 38Case #205: 44 18 4 10 31Case #206: 49 9 16 48 47Case #207: 25 32 22 3 49Case #208: 3 21 25 3 46Case #209: 18 24 20 20 36Case #210: 20 48 37 44 22Case #211: 32 25 40 9 21Case #212: 9 46 14 39 48Case #213: 29 29 41 3 30Case #214: 17 49 23 40 6Case #215: 45 29 46 9 19Case #216: 13 33 5 13 43Case #217: 10 27 36 39 20Case #218: 2 19 22 25 45Case #219: 2 32 42 28 39Case #220: 41 10 31 29 21Case #221: 28 9 44 23 49Case #222: 12 10 5 3 30Case #223: 15 27 42 0 41Case #224: 10 16 16 32 27Case #225: 12 4 20 38 37Case #226: 36 36 12 18 22Case #227: 33 5 25 8 42Case #228: 44 26 28 25 38Case #229: 48 22 32 11 25Case #230: 9 44 11 49 22Case #231: 6 48 21 44 25Case #232: 29 44 44 9 44Case #233: 21 19 31 20 25Case #234: 50 25 29 32 21Case #235: 27 11 30 3 40Case #236: 16 48 32 32 22Case #237: 6 5 35 32 24Case #238: 14 44 19 32 41Case #239: 19 13 48 10 31Case #240: 2 1 32 41 46Case #241: 8 39 12 21 40Case #242: 13 45 10 37 37Case #243: 4 23 11 41 22Case #244: 10 21 7 32 13Case #245: 11 1 10 15 43Case #246: 32 42 21 10 29Case #247: 39 27 12 38 41Case #248: 43 48 36 47 36Case #249: 37 37 48 32 32Case #250: 37 49 1 46 21Case #251: 26 11 46 7 44Case #252: 47 9 48 15 50Case #253: 29 47 19 8 40Case #254: 21 31 40 35 16Case #255: 39 31 46 27 11Case #256: 1 10 8 2 48Case #257: 42 37 5 22 40Case #258: 34 33 17 39 30Case #259: 31 4 28 17 17Case #260: 1 30 44 36 48Case #261: 6 3 29 8 41Case #262: 21 16 18 46 30Case #263: 23 10 42 42 37Case #264: 19 3 4 3 32Case #265: 36 24 36 9 24Case #266: 49 1 27 4 13Case #267: 23 22 29 33 29Case #268: 18 38 21 41 45Case #269: 1 47 4 2 30Case #270: 47 34 44 7 25Case #271: 41 34 26 1 22Case #272: 28 4 28 27 37Case #273: 46 44 39 19 49Case #274: 36 20 30 8 12Case #275: 43 40 35 36 41Case #276: 26 48 9 20 18Case #277: 23 46 15 14 49Case #278: 34 14 50 18 39Case #279: 31 0 29 7 33Case #280: 49 16 43 29 24Case #281: 12 3 38 14 16Case #282: 22 25 30 39 22Case #283: 27 0 30 28 34Case #284: 8 10 48 6 50Case #285: 10 20 43 40 26Case #286: 17 11 19 8 36Case #287: 27 40 16 27 25Case #288: 38 25 21 35 14Case #289: 49 25 20 31 49Case #290: 20 49 42 45 50Case #291: 17 7 1 17 43Case #292: 7 48 14 42 7Case #293: 29 39 4 48 48Case #294: 36 40 27 42 40Case #295: 16 39 17 15 13Case #296: 8 39 37 46 30Case #297: 15 29 13 3 16Case #298: 27 46 9 35 21Case #299: 9 3 14 36 41Case #300: 1 47 8 12 29Case #301: 15 27 30 5 38Case #302: 21 8 3 22 49Case #303: 23 45 25 28 11Case #304: 9 4 8 3 11Case #305: 7 3 1 26 33Case #306: 21 23 23 11 43Case #307: 40 46 35 21 50Case #308: 38 41 39 39 19Case #309: 8 29 14 3 25Case #310: 23 10 11 24 16Case #311: 2 17 20 26 44Case #312: 43 20 7 1 30Case #313: 7 33 27 25 26Case #314: 29 44 18 43 28Case #315: 14 21 8 31 34Case #316: 36 32 2 6 39Case #317: 10 27 34 17 37Case #318: 44 34 22 42 38Case #319: 21 37 49 46 17Case #320: 4 31 15 45 47Case #321: 45 44 39 47 11Case #322: 21 20 35 8 38Case #323: 48 27 43 12 41Case #324: 32 25 38 11 13Case #325: 22 45 16 23 31Case #326: 32 39 6 22 24Case #327: 5 40 10 16 34Case #328: 46 13 26 7 26Case #329: 49 48 46 29 10Case #330: 47 18 35 41 40Case #331: 35 35 41 15 44Case #332: 8 23 12 34 13Case #333: 18 47 30 25 22Case #334: 46 15 14 41 36Case #335: 4 45 14 0 48Case #336: 28 20 17 23 49Case #337: 24 11 6 28 21Case #338: 38 27 18 37 28Case #339: 28 40 7 14 20Case #340: 11 17 2 43 40Case #341: 47 45 13 26 36Case #342: 20 4 14 34 16Case #343: 33 5 14 18 42Case #344: 2 21 21 33 23Case #345: 5 36 20 32 24Case #346: 4 29 23 49 46Case #347: 12 38 14 20 44Case #348: 5 15 35 5 32Case #349: 20 45 38 46 25Case #350: 3 30 6 50 47Case #351: 25 46 14 38 37Case #352: 49 50 19 46 33Case #353: 31 34 41 38 18Case #354: 30 11 12 43 26Case #355: 27 8 33 23 23Case #356: 37 37 1 16 50Case #357: 46 47 16 21 26Case #358: 36 16 5 34 41Case #359: 27 39 21 48 18Case #360: 15 37 21 48 47Case #361: 14 36 38 24 49Case #362: 48 41 6 32 36Case #363: 45 11 40 1 11Case #364: 35 20 0 9 39Case #365: 19 44 42 30 49Case #366: 25 3 30 5 38Case #367: 49 26 45 23 50Case #368: 35 39 37 40 32Case #369: 29 19 26 37 37Case #370: 43 15 48 23 17Case #371: 7 9 15 31 30Case #372: 22 21 39 17 45Case #373: 38 45 3 15 39Case #374: 12 42 13 30 35Case #375: 39 39 44 4 23Case #376: 13 46 33 45 37Case #377: 13 22 15 19 43Case #378: 10 11 20 21 11Case #379: 28 25 24 10 45Case #380: 26 41 6 29 33Case #381: 13 27 1 39 10Case #382: 12 34 16 5 31Case #383: 8 19 24 5 37Case #384: 49 27 48 4 43Case #385: 7 0 31 6 39Case #386: 50 44 29 42 47Case #387: 47 21 44 5 49Case #388: 6 20 19 42 31Case #389: 39 37 16 13 50Case #390: 31 26 26 21 45Case #391: 48 29 35 30 21Case #392: 9 20 18 19 18Case #393: 45 48 4 38 48Case #394: 36 6 43 33 40Case #395: 7 19 44 0 28Case #396: 28 43 14 48 27Case #397: 43 21 47 6 11Case #398: 3 0 6 20 29Case #399: 10 28 8 1 41Case #400: 27 25 49 46 21Case #401: 48 23 14 17 27Case #402: 38 24 22 15 34Case #403: 6 50 1 48 15Case #404: 7 24 23 7 16Case #405: 36 39 13 23 17Case #406: 50 7 42 23 13Case #407: 46 14 38 0 20Case #408: 29 36 27 50 32Case #409: 4 11 28 23 37Case #410: 11 29 37 16 35Case #411: 21 21 19 39 19Case #412: 13 37 27 50 32Case #413: 23 10 29 23 42Case #414: 15 40 23 30 20Case #415: 16 21 35 35 42Case #416: 15 6 5 34 24Case #417: 16 38 27 2 43Case #418: 50 16 45 48 25Case #419: 19 26 45 25 31Case #420: 42 41 8 46 40Case #421: 7 17 6 16 4Case #422: 26 35 41 33 41Case #423: 22 34 37 9 31Case #424: 49 44 37 14 25Case #425: 34 6 23 34 23Case #426: 26 48 50 17 26Case #427: 48 28 8 18 43Case #428: 2 39 6 14 47Case #429: 14 28 26 29 24Case #430: 43 44 17 41 48Case #431: 26 18 36 7 21Case #432: 0 1 7 31 18Case #433: 13 42 29 19 40Case #434: 20 35 13 6 22Case #435: 0 35 11 40 19Case #436: 32 43 50 23 32Case #437: 43 11 10 18 32Case #438: 6 2 8 11 7Case #439: 36 10 29 30 29Case #440: 42 27 25 33 32Case #441: 33 6 14 42 27Case #442: 39 36 49 20 12Case #443: 27 46 23 39 11Case #444: 32 1 10 35 48Case #445: 42 34 36 37 50Case #446: 18 18 8 22 15Case #447: 18 31 23 32 4Case #448: 31 2 41 15 40Case #449: 37 5 30 9 33Case #450: 20 33 16 43 13Case #451: 10 18 35 27 44Case #452: 44 42 48 15 22Case #453: 31 45 50 24 23Case #454: 17 45 41 22 34Case #455: 22 28 5 1 20Case #456: 42 49 2 13 43Case #457: 27 17 20 24 43Case #458: 4 18 22 19 35Case #459: 6 28 3 43 32Case #460: 7 21 3 27 45Case #461: 26 46 20 21 49Case #462: 48 16 4 32 48Case #463: 1 26 26 35 14Case #464: 24 50 46 11 26Case #465: 36 45 39 31 26Case #466: 20 19 20 27 32Case #467: 40 23 38 29 38Case #468: 13 24 37 38 44Case #469: 26 43 2 24 43Case #470: 16 9 24 10 22Case #471: 22 30 49 6 44Case #472: 28 20 30 13 30Case #473: 20 2 34 19 25Case #474: 21 17 40 15 12Case #475: 0 36 14 43 26Case #476: 12 7 48 37 31Case #477: 9 4 27 6 17Case #478: 14 30 2 31 34Case #479: 33 39 28 35 46Case #480: 42 45 27 28 47Case #481: 12 32 45 11 43Case #482: 50 45 29 44 18Case #483: 49 44 34 25 47Case #484: 46 33 9 34 46Case #485: 6 4 7 3 10Case #486: 19 26 29 32 47Case #487: 38 5 4 9 36Case #488: 27 42 24 35 9Case #489: 30 41 43 2 31Case #490: 24 12 33 14 25Case #491: 36 8 20 12 29Case #492: 19 22 12 26 44Case #493: 43 3 31 9 13Case #494: 42 16 48 21 34Case #495: 38 11 22 39 30Case #496: 18 45 16 41 31Case #497: 1 21 28 32 25Case #498: 37 7 29 30 27Case #499: 18 43 2 21 40Case #500: 29 24 31 4 42Case #501: 14 15 17 8 4Case #502: 36 1 41 19 34Case #503: 39 13 39 49 48Case #504: 31 50 32 31 20Case #505: 12 25 3 20 12Case #506: 16 17 39 0 29Case #507: 13 7 38 32 31Case #508: 40 41 10 44 18Case #509: 6 33 2 13 21Case #510: 7 3 29 22 26Case #511: 3 7 33 21 38Case #512: 38 15 8 44 23Case #513: 18 46 23 45 39Case #514: 29 20 50 24 27Case #515: 47 5 21 24 48Case #516: 6 6 37 33 33Case #517: 23 49 30 14 37Case #518: 27 24 6 36 31Case #519: 40 19 17 10 45Case #520: 10 29 15 6 18Case #521: 43 10 21 43 32Case #522: 27 3 48 26 17Case #523: 34 37 50 27 24Case #524: 14 10 9 12 41Case #525: 27 11 50 42 25Case #526: 31 8 25 22 25Case #527: 18 46 36 15 32Case #528: 35 50 19 27 18Case #529: 8 10 4 1 45Case #530: 16 1 41 17 50Case #531: 11 41 35 45 43Case #532: 26 8 32 17 49Case #533: 0 47 11 10 21Case #534: 17 30 26 39 21Case #535: 48 24 23 9 34Case #536: 35 0 23 3 23Case #537: 29 28 26 9 31Case #538: 14 13 47 44 46Case #539: 34 16 26 31 40Case #540: 22 43 27 36 30Case #541: 43 14 5 28 44Case #542: 6 19 27 22 19Case #543: 34 36 27 6 41Case #544: 7 35 16 26 23Case #545: 24 10 11 22 42Case #546: 50 50 40 0 30Case #547: 44 22 25 8 44Case #548: 16 42 10 34 7Case #549: 35 18 24 37 19Case #550: 3 36 1 8 23Case #551: 38 6 4 8 32Case #552: 14 32 2 16 47Case #553: 34 5 33 30 23Case #554: 49 4 42 12 15Case #555: 37 4 36 24 49Case #556: 15 7 30 29 47Case #557: 45 8 23 17 26Case #558: 18 7 34 29 19Case #559: 25 31 4 33 24Case #560: 50 47 36 21 36Case #561: 47 41 33 45 39Case #562: 33 16 13 0 39Case #563: 14 37 26 49 9Case #564: 32 5 31 13 35Case #565: 40 6 24 46 30Case #566: 44 27 15 46 30Case #567: 32 25 23 9 13Case #568: 47 6 30 8 25Case #569: 16 29 23 40 24Case #570: 23 23 6 36 36Case #571: 25 40 15 7 47Case #572: 26 8 36 34 49Case #573: 41 19 2 0 46Case #574: 38 37 46 15 14Case #575: 38 23 11 36 15Case #576: 35 24 32 42 48Case #577: 46 35 47 26 19Case #578: 12 36 6 22 34Case #579: 2 26 14 38 24Case #580: 49 23 36 15 13Case #581: 9 15 48 29 36Case #582: 32 21 9 9 27Case #583: 30 0 8 23 25Case #584: 27 16 47 25 19Case #585: 19 32 3 10 27Case #586: 14 35 9 45 43Case #587: 35 33 4 27 21Case #588: 23 2 4 46 34Case #589: 13 3 19 41 40Case #590: 14 9 48 9 32Case #591: 5 3 3 17 39Case #592: 25 29 33 27 11Case #593: 16 14 19 21 15Case #594: 22 10 1 14 19Case #595: 36 13 1 39 22Case #596: 43 28 26 13 38Case #597: 26 32 27 46 43Case #598: 23 6 33 22 11Case #599: 48 21 21 38 38Case #600: 42 33 48 24 33Case #601: 2 36 20 43 15Case #602: 5 11 47 4 34Case #603: 2 0 28 37 50Case #604: 30 30 50 13 18Case #605: 21 26 37 3 31Case #606: 27 9 35 12 7Case #607: 41 9 20 38 45Case #608: 48 31 7 20 35Case #609: 3 9 28 1 30Case #610: 34 17 42 26 39Case #611: 20 19 16 6 23Case #612: 41 38 16 26 23Case #613: 28 22 15 35 38Case #614: 12 7 20 28 13Case #615: 9 48 33 19 21Case #616: 21 39 8 39 44Case #617: 26 0 37 16 47Case #618: 37 49 24 30 15Case #619: 30 36 11 42 40Case #620: 18 27 22 43 22Case #621: 7 31 26 21 11Case #622: 0 24 5 28 46Case #623: 0 29 26 1 43Case #624: 40 24 40 14 41Case #625: 19 33 50 12 44Case #626: 0 31 24 4 44Case #627: 35 24 35 5 47Case #628: 13 43 26 17 33Case #629: 48 28 43 38 18Case #630: 17 12 49 39 40Case #631: 26 14 38 44 48Case #632: 32 26 16 23 35Case #633: 28 11 18 47 39Case #634: 17 0 41 36 47Case #635: 19 20 24 38 10Case #636: 0 15 24 32 30Case #637: 6 33 0 26 44Case #638: 5 18 5 11 18Case #639: 26 44 50 36 45Case #640: 3 41 47 31 25Case #641: 35 17 26 46 42Case #642: 1 31 27 12 45Case #643: 3 28 21 13 15Case #644: 11 34 8 37 3Case #645: 35 31 22 13 20Case #646: 10 8 13 43 34Case #647: 3 22 46 17 44Case #648: 30 23 35 15 22Case #649: 8 20 40 30 39Case #650: 12 11 16 32 24Case #651: 26 44 35 43 47Case #652: 16 47 31 49 20Case #653: 8 11 49 21 35Case #654: 44 12 0 8 24Case #655: 21 22 41 24 14Case #656: 3 35 43 3 30Case #657: 1 24 5 48 34Case #658: 15 13 22 28 15Case #659: 2 17 8 17 9Case #660: 8 49 13 39 34Case #661: 20 8 32 22 41Case #662: 2 29 27 43 25Case #663: 3 10 2 17 43Case #664: 6 47 43 50 30Case #665: 38 43 35 40 32Case #666: 19 14 33 19 31Case #667: 24 47 4 23 26Case #668: 37 38 0 44 23Case #669: 23 29 42 18 46Case #670: 22 24 41 14 32Case #671: 9 28 39 30 38Case #672: 14 24 7 17 27Case #673: 26 7 23 42 29Case #674: 14 25 36 31 26Case #675: 2 11 31 31 40Case #676: 18 1 35 15 39Case #677: 1 21 35 50 36Case #678: 32 44 34 24 44Case #679: 13 42 19 38 43Case #680: 14 50 1 33 44Case #681: 0 6 2 22 21Case #682: 15 0 28 45 43Case #683: 20 27 32 32 27Case #684: 11 21 14 21 18Case #685: 21 39 20 32 49Case #686: 32 45 0 5 30Case #687: 31 36 38 4 44Case #688: 44 5 30 13 10Case #689: 46 37 11 49 42Case #690: 37 47 42 26 30Case #691: 12 46 13 23 19Case #692: 33 16 27 4 9Case #693: 26 18 19 39 49Case #694: 26 8 44 45 31Case #695: 7 10 28 15 17Case #696: 44 41 40 30 47Case #697: 20 10 49 18 17Case #698: 17 23 45 20 22Case #699: 44 12 14 2 29Case #700: 28 29 19 4 26Case #701: 35 8 30 15 17Case #702: 18 26 50 25 19Case #703: 50 9 46 41 18Case #704: 29 38 49 13 43Case #705: 1 43 20 20 20Case #706: 34 34 10 22 30Case #707: 38 7 46 15 20Case #708: 3 4 29 2 17Case #709: 28 19 42 1 46Case #710: 34 11 23 13 9Case #711: 27 16 42 16 36Case #712: 40 46 46 48 7Case #713: 29 19 7 44 38Case #714: 41 22 32 2 16Case #715: 33 21 24 32 11Case #716: 48 41 41 10 31Case #717: 17 18 17 7 29Case #718: 39 9 13 31 44Case #719: 14 33 44 22 28Case #720: 45 26 39 23 11Case #721: 21 8 7 44 34Case #722: 33 25 34 37 26Case #723: 24 49 24 27 35Case #724: 12 35 19 12 40Case #725: 8 31 16 9 23Case #726: 6 7 33 47 48Case #727: 37 9 29 9 25Case #728: 13 13 5 13 38Case #729: 8 19 41 32 39Case #730: 43 12 46 12 21Case #731: 36 38 41 2 36Case #732: 22 43 20 32 48Case #733: 38 22 39 19 34Case #734: 26 13 37 27 12Case #735: 42 46 49 37 40Case #736: 5 21 41 1 36Case #737: 44 9 47 15 29Case #738: 49 31 42 25 14Case #739: 33 10 0 43 32Case #740: 1 28 24 31 44Case #741: 28 4 13 9 35Case #742: 10 41 11 5 41Case #743: 45 19 24 42 42Case #744: 8 28 5 18 34Case #745: 35 1 25 4 50Case #746: 50 19 14 34 28Case #747: 47 8 47 23 29Case #748: 25 14 42 10 36Case #749: 9 11 36 39 27Case #750: 36 44 35 11 30Case #751: 32 2 25 24 21Case #752: 9 42 31 28 43Case #753: 28 29 1 40 15Case #754: 37 48 9 11 41Case #755: 47 32 12 7 28Case #756: 30 19 19 34 14Case #757: 44 33 30 4 48Case #758: 23 46 36 33 49Case #759: 11 37 10 28 23Case #760: 5 24 29 33 19Case #761: 23 28 21 42 28Case #762: 11 23 28 19 36Case #763: 10 26 8 46 42Case #764: 20 31 50 18 32Case #765: 11 11 15 31 44Case #766: 50 21 41 18 49Case #767: 1 47 41 13 49Case #768: 33 45 31 22 50Case #769: 41 46 28 13 45Case #770: 1 14 49 35 32Case #771: 19 0 10 45 32Case #772: 21 10 45 8 27Case #773: 32 8 40 24 20Case #774: 7 29 27 25 20Case #775: 28 5 10 50 42Case #776: 24 24 28 48 13Case #777: 3 12 18 33 41Case #778: 39 35 31 50 41Case #779: 40 9 18 8 27Case #780: 30 29 11 27 10Case #781: 47 40 17 50 39Case #782: 23 1 43 43 33Case #783: 20 50 30 42 23Case #784: 17 45 28 37 33Case #785: 27 41 47 42 30Case #786: 20 12 6 47 44Case #787: 10 18 31 41 37Case #788: 20 7 31 9 19Case #789: 4 2 11 4 11Case #790: 25 21 3 8 16Case #791: 20 8 4 42 38Case #792: 4 12 12 39 37Case #793: 40 19 34 40 16Case #794: 22 13 28 31 31Case #795: 43 13 6 44 46Case #796: 42 39 34 34 40Case #797: 21 3 16 23 34Case #798: 29 49 7 40 22Case #799: 44 1 11 43 28Case #800: 48 24 26 30 39Case #801: 48 16 20 18 19Case #802: 16 37 13 27 38Case #803: 21 12 5 12 49Case #804: 18 12 7 21 38Case #805: 1 29 12 41 49Case #806: 34 5 26 19 12Case #807: 1 27 14 16 46Case #808: 5 13 10 37 13Case #809: 41 19 29 21 16Case #810: 4 7 42 45 37Case #811: 7 22 19 5 11Case #812: 19 9 38 19 13Case #813: 6 9 12 31 21Case #814: 22 13 10 10 29Case #815: 14 20 35 14 34Case #816: 22 48 10 9 26Case #817: 43 31 25 26 21Case #818: 4 29 21 49 40Case #819: 37 21 7 10 50Case #820: 17 37 43 36 21Case #821: 30 5 34 15 33Case #822: 20 3 11 23 15Case #823: 11 46 38 0 36Case #824: 44 30 7 3 50Case #825: 15 39 22 14 23Case #826: 15 27 31 14 30Case #827: 12 1 10 33 46Case #828: 33 37 40 35 37Case #829: 36 37 49 19 15Case #830: 38 30 0 8 33Case #831: 47 33 35 30 12Case #832: 29 25 33 38 18Case #833: 26 15 4 3 24Case #834: 24 14 36 35 36Case #835: 9 5 22 7 35Case #836: 47 41 17 50 29Case #837: 21 21 29 24 26Case #838: 10 8 17 10 41Case #839: 29 27 24 20 19Case #840: 30 15 17 42 26Case #841: 1 22 15 25 41Case #842: 19 42 6 18 46Case #843: 15 6 3 18 17Case #844: 32 13 48 18 18Case #845: 30 30 5 23 42Case #846: 47 38 34 12 38Case #847: 34 47 41 6 26Case #848: 8 30 17 7 37Case #849: 48 36 1 3 37Case #850: 43 44 37 37 49Case #851: 19 42 27 2 26Case #852: 47 33 33 11 49Case #853: 20 45 39 29 18Case #854: 20 11 29 38 32Case #855: 31 50 22 37 20Case #856: 23 5 39 12 32Case #857: 16 32 4 27 32Case #858: 36 15 47 24 27Case #859: 13 25 7 50 30Case #860: 29 32 45 33 24Case #861: 38 11 5 6 42Case #862: 38 39 49 29 43Case #863: 39 16 47 27 42Case #864: 46 19 49 24 38Case #865: 37 29 46 41 10Case #866: 49 42 32 36 34Case #867: 44 50 24 18 29Case #868: 2 12 12 29 46Case #869: 46 27 37 0 46Case #870: 47 50 27 26 19Case #871: 37 17 33 45 17Case #872: 44 21 47 35 15Case #873: 10 32 22 38 27Case #874: 12 49 17 0 25Case #875: 3 41 7 50 29Case #876: 43 12 32 28 29Case #877: 29 24 49 13 39Case #878: 33 9 46 8 50Case #879: 17 32 23 28 37Case #880: 21 18 16 12 15Case #881: 24 50 22 0 45Case #882: 8 2 12 20 23Case #883: 47 31 27 31 15Case #884: 35 24 26 22 38Case #885: 24 9 0 35 26Case #886: 16 47 44 40 42Case #887: 8 49 47 27 40Case #888: 21 43 2 20 45Case #889: 22 50 1 0 43Case #890: 21 16 30 5 10Case #891: 45 22 18 42 44Case #892: 49 44 47 11 37Case #893: 0 23 46 30 35Case #894: 23 31 41 40 36Case #895: 34 42 8 8 25Case #896: 13 10 6 20 34Case #897: 38 5 15 30 38Case #898: 4 0 48 3 47Case #899: 42 0 10 27 31Case #900: 9 17 16 48 19Case #901: 8 18 15 28 9Case #902: 5 38 1 33 6Case #903: 0 29 19 21 26Case #904: 38 37 37 12 40Case #905: 8 5 39 29 35Case #906: 31 23 38 42 30Case #907: 18 50 50 4 33Case #908: 50 12 41 25 25Case #909: 28 18 36 1 13Case #910: 26 24 1 0 47Case #911: 28 40 12 41 42Case #912: 0 49 19 20 38Case #913: 40 26 37 6 42Case #914: 33 49 12 43 30Case #915: 16 15 43 1 22Case #916: 17 45 14 14 23Case #917: 11 20 12 24 23Case #918: 8 40 38 9 27Case #919: 45 1 45 43 33Case #920: 49 33 2 33 43Case #921: 18 28 18 11 44Case #922: 9 9 17 38 27Case #923: 17 45 6 19 45Case #924: 20 35 4 29 27Case #925: 2 11 15 10 41Case #926: 34 34 24 28 30Case #927: 22 25 28 3 33Case #928: 15 7 19 17 18Case #929: 29 36 9 24 24Case #930: 4 0 25 31 26Case #931: 44 23 3 26 25Case #932: 27 7 12 15 46Case #933: 10 44 1 25 30Case #934: 34 45 46 49 11Case #935: 19 22 15 7 39Case #936: 27 48 38 42 29Case #937: 20 42 19 34 23Case #938: 12 26 45 4 46Case #939: 36 46 40 44 8Case #940: 47 34 39 23 31Case #941: 38 23 32 43 40Case #942: 23 44 9 24 41Case #943: 41 9 1 33 34Case #944: 15 30 37 28 38Case #945: 36 38 42 21 45Case #946: 13 39 22 6 42Case #947: 0 10 41 23 47Case #948: 0 4 50 50 43Case #949: 3 39 15 27 11Case #950: 38 13 45 48 20Case #951: 2 43 3 41 40Case #952: 40 4 15 2 24Case #953: 8 35 28 31 49Case #954: 45 20 46 9 45Case #955: 29 1 21 0 20Case #956: 46 17 9 0 40Case #957: 19 40 30 35 39Case #958: 13 34 19 36 21Case #959: 47 8 37 10 34Case #960: 33 42 0 17 27Case #961: 47 38 38 50 34Case #962: 38 11 25 20 18Case #963: 24 13 29 19 48Case #964: 47 48 16 11 50Case #965: 42 27 17 34 34Case #966: 20 30 36 15 30Case #967: 3 1 33 20 32Case #968: 14 40 27 36 16Case #969: 38 4 35 18 14Case #970: 12 40 41 29 42Case #971: 18 32 26 16 26Case #972: 44 21 39 33 42Case #973: 5 8 16 19 13Case #974: 12 10 18 10 23Case #975: 37 44 13 21 28Case #976: 27 5 23 0 12Case #977: 35 7 29 25 29Case #978: 20 44 20 43 15Case #979: 29 42 13 19 31Case #980: 1 12 41 41 50Case #981: 10 26 33 31 43Case #982: 35 8 39 24 16Case #983: 3 47 17 41 34Case #984: 28 2 14 28 41Case #985: 17 44 16 21 29Case #986: 17 2 10 15 28Case #987: 2 12 18 12 48Case #988: 0 47 18 33 40Case #989: 22 38 22 13 23Case #990: 7 17 38 40 25Case #991: 46 12 40 13 7Case #992: 3 38 50 19 28Case #993: 15 30 23 46 38Case #994: 12 31 11 33 29Case #995: 45 19 45 38 26Case #996: 34 16 8 23 43Case #997: 29 15 20 11 36Case #998: 36 18 35 5 7Case #999: 40 43 18 11 25Case #1000: 19 6 18 8 291234567891011There are many ways you might approach this problem, but a simple one is to find the pair of circles that contain all the given points while minimizing the area of the intersection.
A naive solution tries all ~\(50^5\) possible pairs of circles and does an \(O(N)\) check to confirm that all of the points lie in the intersection of that pair of circles. Even if we downsample to \(500\) points (the minimum guaranteed by the problem), that's still too slow.
We can do some precomputing to make this much faster: for each possible circle center \((x, y)\), the only radius \(R\) we would ever want to use is the smallest one that contains all of the points. This gives us at most \(51^2 \approx 2{,}500\) possible circles to use, and sometimes fewer because \(R\) will be greater than \(50\) for some choices of \((x, y)\).
Now we can simply compute the area of the intersection of each of these \(2{,}500^2 \approx 6{,}000{,}000\) pairs, and select the pair with the smallest intersection. If we encounter a tie, we break it arbitrarily.
Once we've decided which pair of circles to use, we need to decide which one is \(A\) and which one is \(B\). While the function for generating tree locations may look like it spreads trees evenly across a given circle, it's actually biased towards placing trees towards the center of \(A\). The function generates \(r\) uniformly from \([0, R)\), which means (for example) that half of the points will land within a radius of \(R/2\) which is only a quarter of the area of the whole circle. If we compute the sum of distances from each point to the centers of the two circles, the circle with the lower sum is more likely to be \(A\).
Empirically, this approach correctly predicts approximately \(90\%\) of the cases when \(500\) points are sampled.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382#include <algorithm>#include <cstring>#include <iostream>#include <stack>#include <tuple>#include <unordered_set>#include <vector>using namespace std;
const int LIM = 3005;const int MAXN = LIM * LIM;
vector<int> adj[MAXN];unordered_set<int> cutpoints;vector<int> comp;vector<vector<int>> bcc, bcc_adj;
void reset_edges() { for (int i = 0; i < MAXN; i++) { adj[i].clear(); }}
void add_edge(int u, int v) { adj[u].push_back(v); adj[v].push_back(u);}
void tarjan(int N) { cutpoints.clear(); bcc.clear(); comp.assign(N, -1); vector<int> vis(N), parent(N, -1), children(N), tin(N), pushed(N), low(N); vector<bool> is_cut(N); int curr_root = 0; stack<tuple<int, int, int>> dfs; stack<int> st; for (int i = 0; i < N; i++) { if (vis[i]) { continue; } vis[i] = ++curr_root; tin[i] = 0; int timer = 1; dfs.push({i, 0, 0}); while (!dfs.empty()) { auto [u, j, t] = dfs.top(); low[u] = t; if (!pushed[u]) { st.push(u); pushed[u] = 1; } if (j == (int)adj[u].size()) { if ((parent[u] == -1 && children[u] >= 2) || (parent[u] != -1 && is_cut[u])) { cutpoints.insert(u); } if (t >= tin[u]) { vector<int> component; do { int v = st.top(); component.push_back(v); comp[v] = bcc.size(); st.pop(); } while (comp[u] == -1); bcc.push_back(component); } dfs.pop(); continue; } int v = adj[u][j]; if (parent[u] == v) { get<1>(dfs.top())++; continue; } if (vis[v] == 0) { vis[v] = curr_root; parent[v] = u; children[u]++; dfs.push({v, 0, timer}); tin[v] = timer++; continue; } is_cut[u] = is_cut[u] || low[v] >= tin[u]; if (vis[v] == curr_root && comp[v] == -1 && low[v] < t) { get<2>(dfs.top()) = low[v]; } get<1>(dfs.top())++; } } bcc_adj.assign(bcc.size(), {}); for (int i = 0; i < N; i++) { for (int j = 0; j < (int)adj[i].size(); j++) { if (comp[i] != comp[adj[i][j]]) { bcc_adj[comp[i]].push_back(comp[adj[i][j]]); } } }}
template <class Value>class LinkCut { struct Node { int ch[2] = {0, 0}, p = 0; Value self = 0, path = 0; // Path aggregates Value sub = 0, vir = 0; // Subtree aggregates bool flip = 0; // Lazy tags };
vector<Node> T;
void push(int x) { if (x == 0 || !T[x].flip) { return; } int l = T[x].ch[0], r = T[x].ch[1]; T[l].flip ^= 1; T[r].flip ^= 1; swap(T[x].ch[0], T[x].ch[1]); T[x].flip = 0; }
void pull(int x) { int l = T[x].ch[0], r = T[x].ch[1]; push(l); push(r); T[x].path = T[l].path + T[x].self + T[r].path; T[x].sub = T[x].vir + T[l].sub + T[r].sub + T[x].self; }
void set(int x, int d, int y) { T[x].ch[d] = y; T[y].p = x; pull(x); }
void splay(int x) { auto dir = [&](int x) { int p = T[x].p; if (p == 0) { return -1; } return T[p].ch[0] == x ? 0 : T[p].ch[1] == x ? 1 : -1; }; auto rotate = [&](int x) { int y = T[x].p, z = T[y].p, dx = dir(x), dy = dir(y); set(y, dx, T[x].ch[!dx]); set(x, !dx, y); if (~dy) { set(z, dy, x); } T[x].p = z; }; for (push(x); ~dir(x);) { int y = T[x].p, z = T[y].p; push(z); push(y); push(x); int dx = dir(x), dy = dir(y); if (~dy) { rotate(dx != dy ? x : y); } rotate(x); } }
int access(int x) { int v = 0; for (int u = x; u != 0; u = T[u].p) { splay(u); int &ov = T[u].ch[1]; T[u].vir += T[ov].sub; T[u].vir -= T[v].sub; ov = v; pull(u); v = u; } splay(x); return v; }
void reroot(int x) { access(x); T[x].flip ^= 1; push(x); }
public: LinkCut(int n = 0) : T(n + 1) {}
void Init(int u, Value v) { T[++u].self = v; pull(u); }
void Reset(int n) { T.clear(); T.resize(n + 1); }
void Link(int u, int v) { if (u == v || LCA(u, v) != -1) { return; } reroot(++u); access(++v); T[v].vir += T[u].sub; T[u].p = v; pull(v); }
void Cut(int u, int v) { if (u == v || LCA(u, v) == -1) { return; } reroot(++u); access(++v); T[v].ch[0] = T[u].p = 0; pull(v); }
// Rooted tree LCA. Returns -1 if u and v aren't connected. int LCA(int u, int v) { if (++u == ++v) { return u; } access(u); int ret = access(v); return T[u].p ? ret : -1; }
// Query subtree of u where v is outside the subtree. // Pass u = v to get the aggregate for the entire tree containing u. Value Subtree(int u, int v) { reroot(++v); access(++u); return T[u].vir + T[u].self; }
Value Path(int u, int v) { reroot(++u); access(++v); return T[v].path; }
void Update(int u, Value v) { access(++u); T[u].self = v; pull(u); }};
// Main algorithm.
int R, C;int G[LIM][LIM];LinkCut<int> lcf;
inline int getn(int r, int c) { return r * C + c; }inline int getr(int n) { return n / C; }inline int getc(int n) { return n % C; }
// Size of group connected to (r2, c2) after swapping (r1, c1) to (r2, c2).int num_cleared(int r1, int c1, int r2, int c2) { int res = 0; int u = getn(r1, c1), cu = comp[u]; // If u is a cutpoint, disconnect it from all neighboring BCCs. if (cutpoints.count(u)) { for (int v : adj[u]) { int cv = comp[v]; if (cu != cv) { lcf.Cut(cu, cv); } } } // Get a representative for each neighboring group of (r2, c2). unordered_set<int> seen_groups; bool seen_orig = false; // Whether we've seen the original group of cu. for (auto [dr, dc] : {pair{-1, 0}, {0, 1}, {1, 0}, {0, -1}}) { int r3 = r2 + dr, c3 = c2 + dc; if (r3 < 0 || r3 >= R || c3 < 0 || c3 >= C) { continue; } if (!(r1 == r3 && c1 == c3) && G[r1][c1] == G[r3][c3]) { int cv = comp[getn(r3, c3)]; bool seen = false; // Have we seen the same group? for (int cmp : seen_groups) { if (lcf.LCA(cv, cmp) != -1) { seen = true; break; } } if (!seen) { if (lcf.LCA(cu, cv) != -1) { seen_orig = true; } res += lcf.Subtree(cv, cv); seen_groups.insert(cv); } } } // If we didn't encounter the original component, add 1 for the cell itself. if (!seen_orig) { res++; } // Undo disconnections. if (cutpoints.count(u)) { for (int v : adj[u]) { int cv = comp[v]; if (cu != cv) { lcf.Link(cu, cv); } } } return res >= 3 ? res : 0;}
long long solve() { reset_edges(); // Build graph. for (int r = 0; r < R; r++) { for (int c = 0; c < C; c++) { for (auto [dr, dc] : {pair{0, 1}, {1, 0}}) { int r2 = r + dr, c2 = c + dc; if (r2 < 0 || r2 >= R || c2 < 0 || c2 >= C) { continue; } if (G[r][c] == G[r2][c2]) { add_edge(getn(r, c), getn(r2, c2)); } } } } // Compute BCC and block forest. tarjan(R * C); int bcc_nodes = (int)bcc.size(); // Create link-cut forest from BCC. lcf.Reset(bcc_nodes); for (int i = 0; i < bcc_nodes; i++) { lcf.Init(i, bcc[i].size()); } for (int i = 0; i < bcc_nodes; i++) { for (int j : bcc_adj[i]) { lcf.Link(i, j); } } // Try swapping each neighbor. long long ans = 0; for (int r = 0; r < R; r++) { for (int c = 0; c < C; c++) { // Only check right and bottom for ordered pairs. for (auto [dr, dc] : {pair{0, 1}, {1, 0}}) { int r2 = r + dr, c2 = c + dc; if (r2 < 0 || r2 >= R || c2 < 0 || c2 >= C) { continue; } if (G[r][c] != G[r2][c2]) { ans += num_cleared(r, c, r2, c2) + num_cleared(r2, c2, r, c); } } } } return 2 * ans;}
int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; for (int t = 1; t <= T; t++) { memset(G, 0, sizeof G); cin >> R >> C; for (int r = 0; r < R; r++) { for (int c = 0; c < C; c++) { cin >> G[r][c]; } } cout << "Case #" << t << ": " << solve() << endl; } return 0;}123version https://git-lfs.github.com/spec/v1oid sha256:c7988564fd6a6e8beb23b0e2ff6d4cd092af9fe9784bb761f207b128ae3a86b7size 6021899612345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061*Bejeweled*™ is a classic puzzle game where the player tries to match three-in-a-row in a 2D grid of tiles by swapping pairs of adjacent tiles.
*Isblinged*™ is Hacker Cup's spinoff, played on a grid of \(R\) rows by \(C\) columns of tiles. The tile at \((i, j)\) is of an integer type \(G_{i,j}\). A *group* refers to three or more tiles of the same type, connected directly or indirectly via the four orthogonal directions (left, right, up, and down). Initially, the given grid \(G\) may already contain groups.
The player may swap two orthogonally adjacent tiles *of different types*. If the swap results in either tile being in a group of three or more tiles, then all tiles in the *newly-formed group(s)* are cleared.
For the example below (sample case 2), swapping the first two tiles in row \(1\) would clear \(9\) tiles:
{{PHOTO_ID:1310493279783732|WIDTH:700}}
On the other hand, swapping the first two tiles in the second column would clear \(12\) tiles;
{{PHOTO_ID:650302073463012|WIDTH:700}}
Note that the type-3 group is not cleared because it doesn't contain a swapped tile.
Please find the *sum* of tiles that would be cleared over all possible theoretical swaps of ordered pairs of tiles \(G_{i_1, j_1}\) and \(G_{i_2, j_2}\) such that \(|i_1 - i_2| + |j_1 - j_2| = 1\) and \(G_{i_1, j_1} \ne G_{i_2, j_2}\).
# Constraints
\(1 \le T \le 105\)\(1 \le R, C \le 3000\)\(1 \le G_{i,j} \le 10^9\)
The sum of \(R*C\) across all test cases is at most \(40{,}000{,}000\).
# Input Format
Input begins with an integer \(T\), the number of cases. For each case, there is first a line containing two space-separated integers, \(R\) and \(C\). Then, \(R\) lines follow, the \(i\)th of which contains \(C\) space-separated integers \(G_{i,1..C}\).
# Output Format
For the \(i\)th case, print a line containing `"Case #i: "` followed by a single integer, the sum of tiles that can be cleared with a single swap.
# Sample Explanation
In the first sample case:- \(G_{1,1}\), \(G_{1,3}\), and \(G_{2,3}\) can't be swapped with anything that leads to any tiles being cleared.- \(G_{1,2}\) can be swapped with the type-2 tile below to clear \(3\) tiles.- \(G_{2,1}\) can be swapped with the type-2 tile right of it to clear \(3\) tiles.- \(G_{2,2}\) can be swapped with either the type-1 cell above or to the left, each clearing \(3\) tiles.
The answer is therefore \(3 + 3 + 2*3 = 12\).
In the second sample case, the unordered pairs of swaps clearing non-zero numbers of tiles are:- \(G_{1,1} \leftrightarrow G_{1,2} \): clearing \(9\) tiles- \(G_{1,2} \leftrightarrow G_{1,3} \): clearing \(5 + 3 = 8\) tiles- \(G_{1,2} \leftrightarrow G_{2,1} \): clearing \(9 + 3 = 12\) tiles- \(G_{1,3} \leftrightarrow G_{2,3} \): clearing \(5\) tiles- \(G_{1,4} \leftrightarrow G_{2,4} \): clearing \(4\) tiles- \(G_{2,2} \leftrightarrow G_{2,3} \): clearing \(6\) tiles- \(G_{2,2} \leftrightarrow G_{3,2} \): clearing \(4\) tiles- \(G_{2,4} \leftrightarrow G_{2,5} \): clearing \(4\) tiles- \(G_{3,1} \leftrightarrow G_{3,2} \): clearing \(4\) tiles
Doubling the sum for ordered pairs, we get \(2*(9+8+12+5+4+6+4+4+4) = 112\).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105Case #1: 0Case #2: 0Case #3: 1982Case #4: 130Case #5: 0Case #6: 12Case #7: 0Case #8: 0Case #9: 0Case #10: 30Case #11: 32Case #12: 0Case #13: 0Case #14: 23978Case #15: 12582Case #16: 7930Case #17: 0Case #18: 14Case #19: 32Case #20: 18Case #21: 0Case #22: 76Case #23: 40Case #24: 56Case #25: 0Case #26: 68998Case #27: 31032Case #28: 18916Case #29: 0Case #30: 23540Case #31: 12614Case #32: 8064Case #33: 0Case #34: 68582Case #35: 31554Case #36: 18714Case #37: 0Case #38: 200884422Case #39: 24890006Case #40: 12909246Case #41: 0Case #42: 692Case #43: 544Case #44: 8326Case #45: 7928Case #46: 15872Case #47: 8434Case #48: 9084Case #49: 8452Case #50: 122802030Case #51: 15902868Case #52: 8255980Case #53: 5367684Case #54: 1515414Case #55: 417052Case #56: 537018Case #57: 169112Case #58: 24009981167522Case #59: 15986473629556Case #60: 23754469857978Case #61: 1602978Case #62: 23322Case #63: 22302Case #64: 1841520Case #65: 1945100Case #66: 239564Case #67: 1546622Case #68: 0Case #69: 23366Case #70: 0Case #71: 1556198Case #72: 0Case #73: 237642Case #74: 1831920Case #75: 250776Case #76: 242612Case #77: 244878Case #78: 23968Case #79: 1932464Case #80: 0Case #81: 23734Case #82: 0Case #83: 23536Case #84: 244228Case #85: 0Case #86: 23056Case #87: 0Case #88: 0Case #89: 234016Case #90: 23220Case #91: 240212Case #92: 233526Case #93: 240062Case #94: 23662Case #95: 1866038Case #96: 1630710Case #97: 231290Case #98: 232490Case #99: 238914Case #100: 235878Case #101: 1566530Case #102: 0Case #103: 23222Case #104: 0Case #105: 23590212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758Instead of swapping, first imagine shifting a tile \(G_{i,j}\) to replace an adjacent cell at \((i', j')\), leaving behind an empty space (instead of a different tile). Many things can happen:- The tile itself can be disconnected from its old group.- The tile can become connected to a new group.- The tile, moving away, can break up its old group into multiple parts.- The tile, at its new location, can merge different pre-existing groups into one.
Let \(C(i, j, i', j')\) denote the number of type-\(G_{i, j}\) tiles that will be connected to \((i', j')\) after shifting \(G_{i, j}\) to \((i', j')\). We can individually compute \(C(i, j, i', j') + C(i', j', i, j)\) to get the total number of tiles cleared in a single swap \(G_{i, j} \leftrightarrow G_{i',j'}\). The challenge is doing so efficiently.
We can build a graph with a node for each tile and an edge for every pair of adjacent tiles of the same type. There will be \(V = R*C \le 9{,}000{,}000\) nodes and \(E = O(4*R*C)\) edges. We could then theoretically solve the [dynamic connectivity](https://en.wikipedia.org/wiki/Dynamic_connectivity) problem to simulate adding/removing edges for each swap, and querying connected component sizes. Actually, we would only need to delete edges (decremental connectivity), query all neighbors of the new cell, and roll back the deletion using a persistent data structure. Unfortunately, even decremental connectivity is difficult to perform efficiently on general graphs.
Instead, we can try taking advantage of the structure of the graph. If we decompose the graph into [biconnected components](https://en.wikipedia.org/wiki/Biconnected_component) (BCCs), we see that the entire graph is a forest of block-cut trees (one for each tile group) connected by bridges at cut vertices (articulation points). For example, the cut vertices of the second sample case is denoted by asterisks:
```1 2 1 1* 1*1* 1 2 2 1*1 3 3* 3 1```
When we shift \(G_{i, j}\) to a neighboring cell \((i', j')\), there are two cases:
_Case 1_: Tile \(G_{i, j}\) was not a cut vertex: All tiles of the original group will remain connected, except maybe the shifted tile itself. Then, \(C(i, j, i', j')\) can be computed by summing the sizes of groups of type \(G_{i,j}\) that are connected to \((i', j')\). Note that neighbors can be in the same group as each other, or in \(G_{i, j}\)'s original group. We'll need a way to check the connectness of two arbitrary nodes to avoid double counting.
_Case 2_: Tile \(G_{i, j}\) was a cut vertex: We'll need a way to temporarily disconnect it before calculating the group sizes connected to \((i', j')\). The number of edges for the cut vertex (a.k.a. its color) can only be \(2\) or \(3\), for if all \(4\) neighbors were filled, the swap wouldn't be possible.
\(2\)-colored cut vertex examples:```1 1* 1 1 1* 1* 1```\(3\)-colored cut vertex example:``` 1 11 1* 1 1```
In the above cases, each cut vertex is always in its own BCC block, so disconnecting the node is the same as disconnecting the entire block in the block forest.
Working through examples by hand, we see that the only way for a cut vertex to *not* be in its own size-\(1\) block is as follows (left). We have a \(2\)-colored cut vertex but its block is the entire loop:``` 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1* ... 1 --> 1 1 1 1 or 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1```
In this case, the shifted tile may become connected to a different group (middle), or to its own group again (right). Here, we can skip the disconnection/rolling back and just get the total group sizes of the other \(3\) neighbors of \((i', j')\). We'll only add \(1\) if the tile did not get reconnected to its original group.
With these observations, we can obtain the answer by solving dynamic connectivity on the block forest. For each condensed block node, we'll store the number of actual nodes in the block, a.k.a. the block size. We'll need to efficiently:
- delete an edge (and undo the deletion)- check connectivity- query an aggregate function (here, the sum of BCC block sizes) for an entire block tree
One way is with a link-cut forest modified to handle [subtree aggregates](https://usaco.guide/adv/link-cut-tree?lang=cpp#link-cut-tree---subtrees) (full tree queries are just a special case), which can be done with [virtual subtrees](https://codeforces.com/blog/entry/67637#comment-650436). This was the intended solution, and directly supports all of the operations we need. Other approaches include persistent disjoint set union, DFS, and bookkeeping of node component sizes.
Biconnected components and cut vertices can be computed in \(\mathcal{O}(V + E)\) time using Tarjan's algorithm. For each \(C(i, j, i', j')\) calculation, we'll do a constant number of cuts, connectivity checks, and queries on the link-cut forest, taking \(\mathcal{O}(\log V)\) time among them. The overall time complexity to compute the answer across all possible swaps is therefore \(\mathcal{O}(E + V \log V)\)..gitattributes+26
2022/finals/1142476319774543.jpgAdded

Large File Pointer Details
- SHA256: 23d918b889d5d9a7890bd480b1dd37e48046f8a84443aa1ba46f6475f0c675e5
- Pointer size: 130 Bytes
- Size of remote file: 84.1 kB
2022/finals/1175696903384597.jpgAdded

Large File Pointer Details
- SHA256: 58b5e11439c337f27457e68c624171c81c8317839d4cb16bab94f7efeb4f27fd
- Pointer size: 130 Bytes
- Size of remote file: 87.1 kB
2022/finals/1310493279783732.jpgAdded

Large File Pointer Details
- SHA256: 9754b4dac0236e43394160c3918fa987761a7454a3d57549e3044913a8323f31
- Pointer size: 131 Bytes
- Size of remote file: 270 kB
2022/finals/1327255974690671.jpgAdded

Large File Pointer Details
- SHA256: 61ba3755587e5c6f705821ac2be810090c9f839022ad1b4f7b8cf08a62a2dc8e
- Pointer size: 131 Bytes
- Size of remote file: 185 kB
2022/finals/2468652649959145.jpgAdded

Large File Pointer Details
- SHA256: f28a0366297b3f83433d06a38e9ec9ef95fdee972a05167b2e0f33d28f0a9a02
- Pointer size: 131 Bytes
- Size of remote file: 180 kB
2022/finals/504150738360453.jpgAdded

Large File Pointer Details
- SHA256: e0e71f91697efbfe2ddfc6e0b9d3417143c017457a856f804e654220c29e2f7d
- Pointer size: 131 Bytes
- Size of remote file: 169 kB
2022/finals/547949757342773.jpgAdded

Large File Pointer Details
- SHA256: acc1eb8faa045d9bab8aeed7d2208009f8bd51495f4e124a522eb011b777170f
- Pointer size: 131 Bytes
- Size of remote file: 247 kB
2022/finals/556593865835592.jpgAdded

Large File Pointer Details
- SHA256: 0753fe8ac5150ee6ff22ee50784e8febd41ccebcea69077cd2dcae9fac9098fc
- Pointer size: 131 Bytes
- Size of remote file: 126 kB
2022/finals/6502772429739994.jpgAdded

Large File Pointer Details
- SHA256: 87434c6d422cf74bb09356e4eeab99f1bb07570de92bcb097603a5827ed8c835
- Pointer size: 131 Bytes
- Size of remote file: 272 kB
2022/finals/650302073463012.jpgAdded

Large File Pointer Details
- SHA256: 4851ea63addd24a391fbbf166b4f283698fd4739dec4db291bf45ccdb71ada67
- Pointer size: 131 Bytes
- Size of remote file: 285 kB
2022/finals/853886435922998.jpgAdded

Large File Pointer Details
- SHA256: c1cabd26b6e903d6625d9bbfb63175be7eeb52d494c1a7e1248515207ce47ba7
- Pointer size: 131 Bytes
- Size of remote file: 189 kB
2022/finals/876374553707415.jpgAdded

Large File Pointer Details
- SHA256: a936900b3d214fc1360ea2d8bf4812981e7601f4fc232afc6029283f1142c9b7
- Pointer size: 131 Bytes
- Size of remote file: 185 kB
2022/finals/alphabet_adventuring.cppAdded+425
2022/finals/alphabet_adventuring.inAdded+3
2022/finals/alphabet_adventuring.mdAdded+72
2022/finals/alphabet_adventuring.outAdded
2022/finals/alphabet_adventuring_sol.mdAdded+25
2022/finals/cup_counterbalancing.inAdded+42
2022/finals/cup_counterbalancing.javaAdded+397
2022/finals/cup_counterbalancing.mdAdded+34
2022/finals/cup_counterbalancing.outAdded+7
2022/finals/cup_counterbalancing_sol.mdAdded+18
2022/finals/emerald_exhibiting.cppAdded+94
2022/finals/emerald_exhibiting.inAdded+111
2022/finals/emerald_exhibiting.mdAdded+47
2022/finals/emerald_exhibiting.outAdded+110
2022/finals/emerald_exhibiting_sol.mdAdded+18
2022/finals/hazelnut_harvesting.cppAdded+356
2022/finals/hazelnut_harvesting.inAdded+3
2022/finals/hazelnut_harvesting.mdAdded+41
2022/finals/hazelnut_harvesting.outAdded+160
2022/finals/hazelnut_harvesting_sol.mdAdded+21
2022/finals/ml_modeling.cppAdded+102
2022/finals/ml_modeling.inAdded+3
2022/finals/ml_modeling.mdAdded+51
2022/finals/ml_modeling.outAdded+1000
2022/finals/ml_modeling_sol.mdAdded+11
2022/finals/tile_transposing.cppAdded+382
2022/finals/tile_transposing.inAdded+3
2022/finals/tile_transposing.mdAdded+61
2022/finals/tile_transposing.outAdded+105
2022/finals/tile_transposing_sol.mdAdded+58
2022/quals/1183048075593188.jpgAdded

Large File Pointer Details
- SHA256: 4197433f81c95b0bcffa82319c4efbd6a0ab8e89afe33ff90bda1903ac125949
- Pointer size: 130 Bytes
- Size of remote file: 46.6 kB
2022/quals/1264108514364518.jpgAdded

Large File Pointer Details
- SHA256: f59cd2255676091b01b3ebc25e81d6fb5186348b6f56be545fc0d7fac2977c86
- Pointer size: 131 Bytes
- Size of remote file: 409 kB
2022/quals/356437426702208.jpgAdded

Large File Pointer Details
- SHA256: 3392f8efcdf4425c354e5d4bf439755cb51d578330851836e0f7475056406982
- Pointer size: 131 Bytes
- Size of remote file: 115 kB
2022/quals/459254706243127.jpgAdded

Large File Pointer Details
- SHA256: 1db54229bc836348c305b1fc2fee3c3e7bf258f1d6e47cde6de16fc8ff42c209
- Pointer size: 130 Bytes
- Size of remote file: 37.7 kB
2022/quals/5118404751621442.jpgAdded

Large File Pointer Details
- SHA256: 19d99819d9029396ba257897202fd87646cc957027d9ef1a272320998a1bae10
- Pointer size: 131 Bytes
- Size of remote file: 430 kB
2022/quals/545859687328272.jpgAdded

Large File Pointer Details
- SHA256: 3162333722c6059e2d087172028164d1e789152ab059c05ec68842746c7a418f
- Pointer size: 130 Bytes
- Size of remote file: 66.7 kB
2022/quals/569216148234749.jpgAdded

Large File Pointer Details
- SHA256: f59cd2255676091b01b3ebc25e81d6fb5186348b6f56be545fc0d7fac2977c86
- Pointer size: 131 Bytes
- Size of remote file: 409 kB