题面
来源:USACO 官网。模型收到的是同一份题面的文字,不含图片。
You have a bunch of triangular regions that tessellate an infinite 2D plane. The tesselation is defined as follows (see the diagram for a better understanding):
- Recall that Euler's formula states that $e^{ix}=\cos (x)+i\sin (x)$ for real $x$. First, draw a vertex at $x+y\exp(\pi i/3)$ on the complex plane for all integers $x,y$.
- Then for every three vertices from the step above forming an equilateral triangle with side length 1, draw the edges forming its border. Additionally, draw a vertex at the center of the triangle and edges from the center of the triangle to each of three outer vertices.
You are given $N$ ($2\le N\le 2\cdot 10^5$) input points, each of which lies strictly within some region (i.e., not on any vertex or edge). For any pair of the input points, define the distance between them to be the smallest number of edges crossed when drawing a path from one point to the other that doesn't pass through any vertex.
Output the sum of all $N(N-1)/2$ pairwise distances between the input points.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line contains $T$ ($T\ge 1$), the number of independent tests. Each test is specified as follows:The first line contains $N$.
The next $N$ lines each contain three integers $x$, $y$, and $z$ ($0\le x,y<10^6, 0\le z<12$) representing a point at $x+y\exp(\pi i/3)+ \epsilon\cdot \exp((1+2z)\pi i/12)$ on the complex plane ($\epsilon$ being a small positive number).
It is guaranteed that the sum of $N$ over all tests doesn't exceed $2\cdot 10^5$.
OUTPUT FORMAT (print output to the terminal / stdout):
For each test, output the sum of all $N(N-1)/2$ pairwise distances on a new line.SAMPLE INPUT:
6 2 0 0 0 0 0 0 2 0 0 0 1 1 7 2 0 0 0 0 0 6 3 0 0 1 0 0 5 0 0 9 2 0 2 11 1 1 1 2 2 0 11 1 1 1
SAMPLE OUTPUT:
0 3 6 12 2 6
The second test is illustrated below:
- The vertex at $x+y\exp(\pi i/3)$ is labeled with $(x,y)$ for each $x\in[-1,2], y\in[-1,2]$.
- Dots are drawn at the vertices mentioned above as well as the vertices that are the centers of each equilateral triangle.
- The triangular region containing $(x,y,z)=(0,0,0)$ is highlighted in green.
- The triangular region containing $(x,y,z)=(1,1,7)$ is highlighted in blue. Note that $15\pi/12=225^{\circ}$.
- An example path from the first region to the second crossing three edges is drawn.
SCORING:
- Inputs 2-5: $N\le 10$, $0\le x,y<5$
- Inputs 6-13: $N\le 10$
- Inputs 14-21: $T=1$
Problem credits: Benjamin Qi
结果
Kimi K3.1 ProKimi
2/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 28.6采样 3 · 答案错误
- 52.0k平均输出 token(含思考) ↓
- 29.8输出速度 tokens/s ↑
- 2067 秒延迟 ↓
- 0.31×CPU 时间 / 官方解 ↓
- 更优 1、同阶 1时间复杂度(相对官方解)
Kimi K3.1 Pro(high)Kimi high
1/3
解出的采样 ↑
- 100采样 1 · 解出
- 28.6采样 2 · 答案错误
- 61.9采样 3 · 答案错误
- 56.3k平均输出 token(含思考) ↓
- 25.3输出速度 tokens/s ↑
- 2406 秒延迟 ↓
- 0.23×CPU 时间 / 官方解 ↓
- 更优 1时间复杂度(相对官方解)
DeepSeek Flash V4.1-1017DeepSeek
2/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 0.0采样 3 · 答案错误
- 92.9k平均输出 token(含思考) ↓
- 169.1输出速度 tokens/s ↑
- 588 秒延迟 ↓
- 0.27×CPU 时间 / 官方解 ↓
- 更优 2时间复杂度(相对官方解)
MiniMax M3.1 FlashMiniMax
1/3
解出的采样 ↑
- 0.0采样 1 · 编译错误
- 14.3采样 2 · 答案错误
- 100采样 3 · 解出
- 73.2k平均输出 token(含思考) ↓
- 78.4输出速度 tokens/s ↑
- 974 秒延迟 ↓
- 0.23×CPU 时间 / 官方解 ↓
- 更优 1时间复杂度(相对官方解)
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct Node { array<int, 3> c; int port; int type; // 0 = A, 1 = B int same = 1; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); static const int offset[12][3] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 1}, {0, 0, 1}, {-1, 0, 1}, {-1, 0, 1}, {-1, 1, 1}, {-1, 1, 1}, {-1, 1, 0}, {-1, 1, 0}, {0, 1, 0}, {0, 1, 0} }; static const int port[12] = { 1, 2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1 }; int T; cin >> T; while (T--) { int N; cin >> N; vector<Node> nodes(N); array<vector<int>, 3> values; for (int d = 0; d < 3; ++d) { values[d].reserve(N); } for (int i = 0; i < N; ++i) { int x, y, z; cin >> x >> y >> z; array<int, 3> translation = {x + y, -y, -x}; for (int d = 0; d < 3; ++d) { nodes[i].c[d] = translation[d] + offset[z][d]; values[d].push_back(nodes[i].c[d]); } nodes[i].port = port[z]; nodes[i].type = ((z / 2) % 2); // A, A, B, B, ... } for (int d = 0; d < 3; ++d) { sort(values[d].begin(), values[d].end()); } // Sum of L1 distances over all unordered pairs. int64 l1Sum = 0; for (int d = 0; d < 3; ++d) { int64 prefix = 0; for (int i = 0; i < N; ++i) { l1Sum += int64(i) * values[d][i] - prefix; prefix += values[d][i]; } } // Group points having the same base coordinate. vector<int> order(N); iota(order.begin(), order.end(), 0); sort(order.begin(), order.end(), [&](int a, int b) { return nodes[a].c < nodes[b].c; }); int64 sameBasePairs = 0; int64 sameBaseDistance = 0; for (int l = 0; l < N; ) { int r = l + 1; while (r < N && nodes[order[l]].c == nodes[order[r]].c) { ++r; } int sz = r - l; int64 cnt[3] = {0, 0, 0}; for (int i = l; i < r; ++i) { int id = order[i]; nodes[id].same = sz; ++cnt[nodes[id].port]; } sameBasePairs += int64(sz) * (sz - 1) / 2; sameBaseDistance += cnt[0] * cnt[1] + cnt[0] * cnt[2] + cnt[1] * cnt[2]; l = r; } // Sum the independently determined endpoint penalties. int64 penalties = 0; for (const Node &node : nodes) { int d = node.port; int coordinate = node.c[d]; int64 favorable; if (node.type == 0) { // A prefers the coordinate of the other endpoint to be larger. favorable = values[d].end() - upper_bound(values[d].begin(), values[d].end(), coordinate); } else { // B prefers it to be smaller. favorable = lower_bound(values[d].begin(), values[d].end(), coordinate) - values[d].begin(); } penalties += (N - node.same) - favorable; } // Correction for opposite-type pairs whose two endpoint penalties // cannot both be avoided. int64 correction = 0; for (int d = 0; d < 3; ++d) { vector<int> bValues; vector<array<int, 3>> bCoordinates; for (const Node &node : nodes) { if (node.type == 1 && node.port == d) { bValues.push_back(node.c[d]); bCoordinates.push_back(node.c); } } sort(bValues.begin(), bValues.end()); sort(bCoordinates.begin(), bCoordinates.end()); for (const Node &node : nodes) { if (node.type != 0 || node.port != d) { continue; } int wanted = node.c[d] + 1; auto rangeValues = equal_range( bValues.begin(), bValues.end(), wanted ); int64 candidates = rangeValues.second - rangeValues.first; array<int, 3> direct = node.c; ++direct[d]; auto rangeDirect = equal_range( bCoordinates.begin(), bCoordinates.end(), direct ); int64 directNeighbors = rangeDirect.second - rangeDirect.first; correction += candidates - directNeighbors; } } int64 totalPairs = int64(N) * (N - 1) / 2; int64 distinctBasePairs = totalPairs - sameBasePairs; int64 answer = 2 * l1Sum - distinctBasePairs + sameBaseDistance + penalties + correction; cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct CustomHash { static uint64_t mix(uint64_t x) { x += 0x9e3779b97f4a7c15ULL; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL; x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t seed = chrono::steady_clock::now().time_since_epoch().count(); return mix(x + seed); } }; struct Node { int type, x, y, s; }; struct Region { Node c, f; int port; array<int, 3> id; }; static Node makeNode(int type, int x, int y) { return {type, x, y, x + y}; } static int64 coordKey(int x, int y) { return (int64(x + 100) << 32) | uint32_t(y + 100); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); const int dx[6] = {1, 0, -1, -1, 0, 1}; const int dy[6] = {0, 1, 1, 0, -1, -1}; int T; cin >> T; while (T--) { int N; cin >> N; vector<Region> regions(N); array<vector<Node>, 3> uPorts, dPorts; vector<array<int, 3>> ids; ids.reserve(N); for (int i = 0; i < N; i++) { int x, y, z; cin >> x >> y >> z; int j, px, py; if (z % 2 == 0) { j = z / 2; px = x; py = y; } else { j = (z - 5) / 2; if (j < 0) j += 6; px = x - dx[j]; py = y - dy[j]; } Region r{}; switch (j) { case 0: r.c = makeNode(0, px, py); r.f = makeNode(1, px, py - 1); r.port = 2; break; case 1: r.c = makeNode(1, px - 1, py); r.f = makeNode(0, px, py); r.port = 1; break; case 2: r.c = makeNode(0, px - 1, py); r.f = makeNode(1, px - 1, py); r.port = 0; break; case 3: r.c = makeNode(1, px - 1, py - 1); r.f = makeNode(0, px - 1, py); r.port = 2; break; case 4: r.c = makeNode(0, px, py - 1); r.f = makeNode(1, px - 1, py - 1); r.port = 1; break; default: r.c = makeNode(1, px, py - 1); r.f = makeNode(0, px, py - 1); r.port = 0; break; } r.id = {px, py, j}; regions[i] = r; ids.push_back(r.id); if (r.c.type == 0) uPorts[r.port].push_back(r.c); else dPorts[r.port].push_back(r.c); } vector<int> xs, ys, ss, us, ds; xs.reserve(N); ys.reserve(N); ss.reserve(N); us.reserve(N); ds.reserve(N); for (const auto &r : regions) { xs.push_back(r.c.x); ys.push_back(r.c.y); ss.push_back(r.c.s); if (r.c.type == 0) us.push_back(r.c.s); else ds.push_back(r.c.s); } sort(xs.begin(), xs.end()); sort(ys.begin(), ys.end()); sort(ss.begin(), ss.end()); sort(us.begin(), us.end()); sort(ds.begin(), ds.end()); vector<int64> px(N + 1, 0), py(N + 1, 0), ps(N + 1, 0); for (int i = 0; i < N; i++) { px[i + 1] = px[i] + xs[i]; py[i + 1] = py[i] + ys[i]; ps[i + 1] = ps[i] + ss[i]; } auto absSum = [](const vector<int> &v, const vector<int64> &pref, int value) -> int64 { int n = (int)v.size(); int k = lower_bound(v.begin(), v.end(), value) - v.begin(); int64 left = pref[k]; int64 right = pref[n] - left; return int64(value) * k - left + right - int64(value) * (n - k); }; auto query = [&](const Node &p) -> int64 { int64 result = absSum(xs, px, p.x) + absSum(ys, py, p.y) + absSum(ss, ps, p.s); if (p.type == 0) { int64 less = lower_bound(ds.begin(), ds.end(), p.s) - ds.begin(); result += int64(ds.size()) - 2 * less; } else { int64 greater = us.end() - upper_bound(us.begin(), us.end(), p.s); result += int64(us.size()) - 2 * greater; } return result; }; int64 sumC = 0, sumF = 0; for (const auto &r : regions) { sumC += query(r.c); sumF += query(r.f); } int64 base = (sumC + sumF - N) / 2; using Map = unordered_map<int64, int, CustomHash>; auto getCount = [](const Map &m, int64 key) -> int64 { auto it = m.find(key); return it == m.end() ? 0 : int64(it->second); }; int64 compatibility = 0; for (int port = 0; port < 3; port++) { const auto &U = uPorts[port]; const auto &D = dPorts[port]; if (U.empty() || D.empty()) continue; Map primary, exact; primary.reserve(D.size() * 2 + 1); exact.reserve(D.size() * 2 + 1); if (port == 0) { for (const auto &d : D) { primary[d.s]++; exact[coordKey(d.x, d.y)]++; } for (const auto &u : U) { compatibility += getCount(primary, u.s) - getCount(exact, coordKey(u.x, u.y)); } } else if (port == 1) { for (const auto &d : D) { primary[d.x]++; exact[coordKey(d.x, d.y)]++; } for (const auto &u : U) { int wantedX = u.x - 1; compatibility += getCount(primary, wantedX) - getCount(exact, coordKey(wantedX, u.y)); } } else { for (const auto &d : D) { primary[d.y]++; exact[coordKey(d.x, d.y)]++; } for (const auto &u : U) { int wantedY = u.y - 1; compatibility += getCount(primary, wantedY) - getCount(exact, coordKey(u.x, wantedY)); } } } sort(ids.begin(), ids.end()); int64 duplicates = 0; for (int i = 0; i < N;) { int j = i + 1; while (j < N && ids[j] == ids[i]) j++; int64 count = j - i; duplicates += count * (count - 1) / 2; i = j; } cout << base + compatibility - duplicates << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; struct State { array<ll, 3> p; int o; }; // Tail-triangle offsets and orientation for each input sector z. const int OX[12] = {0, 0, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0}; const int OY[12] = {0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1}; const int TP[12] = {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1}; const int DR[12] = {2, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 2}; // Outgoing unit vector for orientation o: coordinate AXIS[o], sign SGN[o]. const int AXIS[6] = {2, 0, 1, 2, 0, 1}; const int SGN[6] = {1, -1, -1, -1, 1, 1}; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; vector<State> a(N); map<array<ll, 4>, ll> stateFreq; map<pair<int, ll>, ll> orientCoordFreq; for (int i = 0; i < N; i++) { ll x, y; int z; cin >> x >> y >> z; ll tx = x + OX[z]; ll ty = y + OY[z]; int type = TP[z]; int o = 3 * type + DR[z]; a[i].p = {tx, ty, tx + ty + type}; a[i].o = o; stateFreq[{tx, ty, tx + ty + type, (ll)o}]++; orientCoordFreq[{o, a[i].p[AXIS[o]]}]++; } // A = sum of L1 distances between tail points over unordered pairs. // S = sum of all ordered geodesic-start indicators. ll A = 0, S = 0; vector<ll> vals; vals.reserve(N); for (int axis = 0; axis < 3; axis++) { vals.clear(); for (const auto &st : a) vals.push_back(st.p[axis]); sort(vals.begin(), vals.end()); ll prefix = 0; for (int i = 0; i < N; i++) { A += 1LL * i * vals[i] - prefix; prefix += vals[i]; } for (const auto &st : a) { int o = st.o; if (AXIS[o] != axis) continue; ll v = st.p[axis]; if (SGN[o] > 0) { S += vals.end() - upper_bound(vals.begin(), vals.end(), v); } else { S += lower_bound(vals.begin(), vals.end(), v) - vals.begin(); } } } // Count ordered candidates for the exceptional incompatibility term. ll candidates = 0, reverseOrdered = 0; for (const auto &st : a) { int o = st.o; int axis = AXIS[o]; int opp = o ^ 3; auto it = orientCoordFreq.find( {opp, st.p[axis] + SGN[o]} ); if (it != orientCoordFreq.end()) candidates += it->second; // The reverse dart has tail p+u and opposite orientation. array<ll, 3> q = st.p; q[axis] += SGN[o]; auto jt = stateFreq.find({q[0], q[1], q[2], (ll)opp}); if (jt != stateFreq.end()) reverseOrdered += jt->second; } ll incompatibilityPairs = (candidates - reverseOrdered) / 2; ll duplicatePairs = 0; for (const auto &kv : stateFreq) { ll f = kv.second; duplicatePairs += f * (f - 1) / 2; } ll pairCount = 1LL * N * (N - 1) / 2; ll answer = 2 * A + pairCount - S + incompatibilityPairs - duplicatePairs; cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct Node { array<int, 3> c; int port; int type; // 0 = A, 1 = B int same = 1; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); static const int offset[12][3] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 1}, {0, 0, 1}, {-1, 0, 1}, {-1, 0, 1}, {-1, 1, 1}, {-1, 1, 1}, {-1, 1, 0}, {-1, 1, 0}, {0, 1, 0}, {0, 1, 0} }; static const int port[12] = { 1, 2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1 }; int T; cin >> T; while (T--) { int N; cin >> N; vector<Node> nodes(N); array<vector<int>, 3> values; for (int d = 0; d < 3; ++d) { values[d].reserve(N); } for (int i = 0; i < N; ++i) { int x, y, z; cin >> x >> y >> z; array<int, 3> translation = {x + y, -y, -x}; for (int d = 0; d < 3; ++d) { nodes[i].c[d] = translation[d] + offset[z][d]; values[d].push_back(nodes[i].c[d]); } nodes[i].port = port[z]; nodes[i].type = ((z / 2) % 2); // A, A, B, B, ... } for (int d = 0; d < 3; ++d) { sort(values[d].begin(), values[d].end()); } // Sum of L1 distances over all unordered pairs. int64 l1Sum = 0; for (int d = 0; d < 3; ++d) { int64 prefix = 0; for (int i = 0; i < N; ++i) { l1Sum += int64(i) * values[d][i] - prefix; prefix += values[d][i]; } } // Group points having the same base coordinate. vector<int> order(N); iota(order.begin(), order.end(), 0); sort(order.begin(), order.end(), [&](int a, int b) { return nodes[a].c < nodes[b].c; }); int64 sameBasePairs = 0; int64 sameBaseDistance = 0; for (int l = 0; l < N; ) { int r = l + 1; while (r < N && nodes[order[l]].c == nodes[order[r]].c) { ++r; } int sz = r - l; int64 cnt[3] = {0, 0, 0}; for (int i = l; i < r; ++i) { int id = order[i]; nodes[id].same = sz; ++cnt[nodes[id].port]; } sameBasePairs += int64(sz) * (sz - 1) / 2; sameBaseDistance += cnt[0] * cnt[1] + cnt[0] * cnt[2] + cnt[1] * cnt[2]; l = r; } // Sum the independently determined endpoint penalties. int64 penalties = 0; for (const Node &node : nodes) { int d = node.port; int coordinate = node.c[d]; int64 favorable; if (node.type == 0) { // A prefers the coordinate of the other endpoint to be larger. favorable = values[d].end() - upper_bound(values[d].begin(), values[d].end(), coordinate); } else { // B prefers it to be smaller. favorable = lower_bound(values[d].begin(), values[d].end(), coordinate) - values[d].begin(); } penalties += (N - node.same) - favorable; } // Correction for opposite-type pairs whose two endpoint penalties // cannot both be avoided. int64 correction = 0; for (int d = 0; d < 3; ++d) { vector<int> bValues; vector<array<int, 3>> bCoordinates; for (const Node &node : nodes) { if (node.type == 1 && node.port == d) { bValues.push_back(node.c[d]); bCoordinates.push_back(node.c); } } sort(bValues.begin(), bValues.end()); sort(bCoordinates.begin(), bCoordinates.end()); for (const Node &node : nodes) { if (node.type != 0 || node.port != d) { continue; } int wanted = node.c[d] + 1; auto rangeValues = equal_range( bValues.begin(), bValues.end(), wanted ); int64 candidates = rangeValues.second - rangeValues.first; array<int, 3> direct = node.c; ++direct[d]; auto rangeDirect = equal_range( bCoordinates.begin(), bCoordinates.end(), direct ); int64 directNeighbors = rangeDirect.second - rangeDirect.first; correction += candidates - directNeighbors; } } int64 totalPairs = int64(N) * (N - 1) / 2; int64 distinctBasePairs = totalPairs - sameBasePairs; int64 answer = 2 * l1Sum - distinctBasePairs + sameBaseDistance + penalties + correction; cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; using uint64 = unsigned long long; struct Point { int x, y; unsigned char ori, label, group; }; struct Stats { int64 sx = 0, sy = 0; uint64 packed0 = 0, packed1 = 0; void clear() { sx = sy = 0; packed0 = packed1 = 0; } void addPoint(const Point &p) { sx += p.x; sy += p.y; if (p.group < 3) packed0 += uint64(1) << (21 * p.group); else packed1 += uint64(1) << (21 * (p.group - 3)); } void addStats(const Stats &other) { sx += other.sx; sy += other.sy; packed0 += other.packed0; packed1 += other.packed1; } }; static const int UX[3] = {1, 1, -2}; static const int UY[3] = {-2, 1, 1}; static const int SX[6] = {1, -1, -2, -1, 1, 2}; static const int SY[6] = {1, 2, 1, -1, -2, -1}; static const int LINX[12] = {2, 2, 0, -2, -2, 0, 2, -2, 2, -2, 0, 0}; static const int LINY[12] = {2, 0, -2, -2, 0, 2, 0, 0, 0, 0, 2, -2}; int genericK[12][6][6]; static inline int64 honeycombHeight(int64 dx, int64 dy) { int64 s = llabs(dx) + llabs(dy) + llabs(dx + dy); return (s + 1) / 3; } static inline int64 displacementS(int64 dx, int64 dy) { return llabs(dx) + llabs(dx) * 0 + llabs(dy) + llabs(dx + dy); } int geodesicMask(int dx, int dy, int ori) { int64 h = honeycombHeight(dx, dy); int mask = 0; for (int a = 0; a < 3; ++a) { int nx = dx + (ori == 0 ? -UX[a] : UX[a]); int ny = dy + (ori == 0 ? -UY[a] : UY[a]); if (honeycombHeight(nx, ny) == h - 1) mask |= 1 << a; } return mask; } void initializeGenericTable() { const int baseX[12] = { 90, 90, 30, -90, -90, -30, 90, -90, 90, -90, 0, 0 }; const int baseY[12] = { 90, -30, -90, -90, 30, 90, 0, 0, -90, 90, 90, -90 }; memset(genericK, 0, sizeof(genericK)); for (int cat = 0; cat < 12; ++cat) { for (int o = 0; o < 2; ++o) { for (int q = 0; q < 2; ++q) { if (cat >= 6 && o != q) continue; int rx = 0, ry = 0; if (o != q) { int r = (o == 0 ? 1 : 2); rx = ry = r; } int dx = baseX[cat] + rx; int dy = baseY[cat] + ry; int64 s = displacementS(dx, dy); int rem = int((s + 1) % 3); int first = geodesicMask(dx, dy, o); int last = geodesicMask(-dx, -dy, q); for (int a = 0; a < 3; ++a) { for (int b = 0; b < 3; ++b) { int turns = ((first & (1 << a)) ? 0 : 1) + ((last & (1 << b)) ? 0 : 1); genericK[cat][o * 3 + a][q * 3 + b] = 3 * turns - 1 - 2 * rem; } } } } } } struct CloseRecord { int dx, dy, endOri; int dist[9]; }; vector<CloseRecord> closeRecords[2]; void enumerateEndpointPaths( int cx, int cy, int co, int step, int h, int tx, int ty, int targetOri, int first, int last, int &mask ) { if (step == h) { if (cx == tx && cy == ty && co == targetOri) mask |= 1 << (first * 3 + last); return; } for (int a = 0; a < 3; ++a) { int nx = cx + (co == 0 ? UX[a] : -UX[a]); int ny = cy + (co == 0 ? UY[a] : -UY[a]); int nf = (step == 0 ? a : first); enumerateEndpointPaths( nx, ny, 1 - co, step + 1, h, tx, ty, targetOri, nf, a, mask ); } } void initializeCloseRecords() { struct Node { int x, y, o; }; for (int startOri = 0; startOri < 2; ++startOri) { map<pair<int,int>, int> reached; vector<Node> cur = {{0, 0, startOri}}; reached[{0, 0}] = startOri; for (int depth = 0; depth < 3; ++depth) { vector<Node> nxt; for (const Node &v : cur) { for (int a = 0; a < 3; ++a) { int nx = v.x + (v.o == 0 ? UX[a] : -UX[a]); int ny = v.y + (v.o == 0 ? UY[a] : -UY[a]); nxt.push_back({nx, ny, 1 - v.o}); reached[{nx, ny}] = 1 - v.o; } } cur.swap(nxt); } for (const auto &entry : reached) { int dx = entry.first.first; int dy = entry.first.second; int h = int(honeycombHeight(dx, dy)); if (h == 0 || h > 3) continue; CloseRecord rec; rec.dx = dx; rec.dy = dy; rec.endOri = entry.second; int endpointMask = 0; enumerateEndpointPaths( 0, 0, startOri, 0, h, dx, dy, rec.endOri, 0, 0, endpointMask ); for (int a = 0; a < 3; ++a) { for (int b = 0; b < 3; ++b) { int bestTurns = 2; for (int f = 0; f < 3; ++f) { for (int l = 0; l < 3; ++l) { if (!(endpointMask & (1 << (f * 3 + l)))) continue; bestTurns = min( bestTurns, int(f != a) + int(l != b) ); } } rec.dist[a * 3 + b] = 2 * h - 1 + bestTurns; } } closeRecords[startOri].push_back(rec); } } } int categoryOf(int dx, int dy) { int dz = dx + dy; if (dx == 0) return dy > 0 ? 10 : 11; if (dy == 0) return dx > 0 ? 6 : 7; if (dz == 0) return dx > 0 ? 8 : 9; if (dx > 0 && dy > 0) return 0; if (dx < 0 && dy < 0) return 3; if (dx > 0 && dy < 0) return dz > 0 ? 1 : 2; return dz < 0 ? 4 : 5; } struct Fenwick { int n = 0; vector<Stats> tree; void init(int n_) { n = n_; tree.assign(n + 1, Stats()); } void update(int pos, const Point &p) { for (int i = pos; i <= n; i += i & -i) tree[i].addPoint(p); } Stats query(int pos) const { Stats result; for (int i = pos; i > 0; i -= i & -i) result.addStats(tree[i]); return result; } }; static inline void unpackCounts(const Stats &s, int64 cnt[6]) { const uint64 mask = (uint64(1) << 21) - 1; for (int g = 0; g < 3; ++g) { cnt[g] = int64((s.packed0 >> (21 * g)) & mask); cnt[g + 3] = int64((s.packed1 >> (21 * g)) & mask); } } static inline void accumulateBatch( const Point &target, const Stats &sources, int cat, int64 &orderedSum ) { int64 cnt[6]; unpackCounts(sources, cnt); int64 total = 0; int64 extra = 0; for (int g = 0; g < 6; ++g) { total += cnt[g]; extra += cnt[g] * genericK[cat][g][target.group]; } if (total == 0) return; int64 sumDx = total * int64(target.x) - sources.sx; int64 sumDy = total * int64(target.y) - sources.sy; int64 sumS = LINX[cat] * sumDx + LINY[cat] * sumDy; orderedSum += (2 * sumS + extra) / 3; } struct SplitMixHash { static uint64 splitmix64(uint64 x) { x += 0x9e3779b97f4a7c15ULL; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL; x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL; return x ^ (x >> 31); } size_t operator()(uint64 x) const { static const uint64 seed = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + seed); } }; static inline uint64 centerKey(int x, int y) { return (uint64(uint32_t(x)) << 32) | uint64(uint32_t(y)); } int64 solveTest(vector<Point> &pts) { const int n = int(pts.size()); int64 orderedGeneric = 0; vector<int> ids(n); iota(ids.begin(), ids.end(), 0); // Six open 60-degree sectors: strict two-dimensional dominance. for (int cat = 0; cat < 6; ++cat) { vector<int> U(n), V(n), compressed; compressed.reserve(n); for (int i = 0; i < n; ++i) { int x = pts[i].x, y = pts[i].y; if (cat == 0) { U[i] = x; V[i] = y; } else if (cat == 1) { U[i] = -y; V[i] = x + y; } else if (cat == 2) { U[i] = x; V[i] = -x - y; } else if (cat == 3) { U[i] = -x; V[i] = -y; } else if (cat == 4) { U[i] = y; V[i] = -x - y; } else { U[i] = -x; V[i] = x + y; } compressed.push_back(V[i]); } sort(compressed.begin(), compressed.end()); compressed.erase(unique(compressed.begin(), compressed.end()), compressed.end()); sort(ids.begin(), ids.end(), [&](int a, int b) { if (U[a] != U[b]) return U[a] < U[b]; return a < b; }); Fenwick bit; bit.init(int(compressed.size())); int pos = 0; while (pos < n) { int end = pos; while (end < n && U[ids[end]] == U[ids[pos]]) ++end; for (int j = pos; j < end; ++j) { int id = ids[j]; int lessV = int(lower_bound( compressed.begin(), compressed.end(), V[id] ) - compressed.begin()); Stats sources = bit.query(lessV); accumulateBatch(pts[id], sources, cat, orderedGeneric); } for (int j = pos; j < end; ++j) { int id = ids[j]; int vp = int(lower_bound( compressed.begin(), compressed.end(), V[id] ) - compressed.begin()) + 1; bit.update(vp, pts[id]); } pos = end; } } // Six rays: one linear form is equal, the other strictly increases. for (int cat = 6; cat < 12; ++cat) { vector<int> eq(n), var(n); for (int i = 0; i < n; ++i) { int x = pts[i].x, y = pts[i].y; if (cat == 6) { eq[i] = y; var[i] = x; } else if (cat == 7) { eq[i] = y; var[i] = -x; } else if (cat == 8) { eq[i] = x + y; var[i] = x; } else if (cat == 9) { eq[i] = x + y; var[i] = -x; } else if (cat == 10) { eq[i] = x; var[i] = y; } else { eq[i] = x; var[i] = -y; } } sort(ids.begin(), ids.end(), [&](int a, int b) { if (eq[a] != eq[b]) return eq[a] < eq[b]; if (var[a] != var[b]) return var[a] < var[b]; return a < b; }); int pos = 0; while (pos < n) { int eqEnd = pos; while (eqEnd < n && eq[ids[eqEnd]] == eq[ids[pos]]) ++eqEnd; Stats prefix; int cur = pos; while (cur < eqEnd) { int end = cur; while (end < eqEnd && var[ids[end]] == var[ids[cur]]) ++end; for (int j = cur; j < end; ++j) { int id = ids[j]; accumulateBatch(pts[id], prefix, cat, orderedGeneric); } for (int j = cur; j < end; ++j) prefix.addPoint(pts[ids[j]]); cur = end; } pos = eqEnd; } } struct CenterGroup { int x, y, ori; int64 count[3] = {0, 0, 0}; }; sort(ids.begin(), ids.end(), [&](int a, int b) { if (pts[a].x != pts[b].x) return pts[a].x < pts[b].x; if (pts[a].y != pts[b].y) return pts[a].y < pts[b].y; return a < b; }); vector<CenterGroup> groups; for (int id : ids) { if (groups.empty() || groups.back().x != pts[id].x || groups.back().y != pts[id].y) { CenterGroup g; g.x = pts[id].x; g.y = pts[id].y; g.ori = pts[id].ori; groups.push_back(g); } groups.back().count[pts[id].label]++; } int64 sameCenter = 0; unordered_map<uint64, int, SplitMixHash> where; where.reserve(groups.size() * 2 + 10); for (int i = 0; i < int(groups.size()); ++i) { const auto &g = groups[i]; sameCenter += g.count[0] * g.count[1] + g.count[0] * g.count[2] + g.count[1] * g.count[2]; where[centerKey(g.x, g.y)] = i; } // At center distance at most three, endpoint geodesics can be // incompatible. Replace the generic value by the exact local value. int64 correction = 0; for (int gi = 0; gi < int(groups.size()); ++gi) { const auto &p = groups[gi]; for (const CloseRecord &rec : closeRecords[p.ori]) { int qx = p.x + rec.dx; int qy = p.y + rec.dy; if (qx < p.x || (qx == p.x && qy <= p.y)) continue; auto it = where.find(centerKey(qx, qy)); if (it == where.end()) continue; const auto &q = groups[it->second]; int cat = categoryOf(rec.dx, rec.dy); int64 s = displacementS(rec.dx, rec.dy); for (int a = 0; a < 3; ++a) { if (!p.count[a]) continue; for (int b = 0; b < 3; ++b) { if (!q.count[b]) continue; int sourceGroup = p.ori * 3 + a; int targetGroup = q.ori * 3 + b; int genericDistance = int( (2 * s + genericK[cat][sourceGroup][targetGroup]) / 3 ); int exactDistance = rec.dist[a * 3 + b]; correction += p.count[a] * q.count[b] * int64(exactDistance - genericDistance); } } } } return sameCenter + orderedGeneric / 2 + correction; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); initializeGenericTable(); initializeCloseRecords(); int T; cin >> T; while (T--) { int N; cin >> N; vector<Point> pts; pts.reserve(N); for (int i = 0; i < N; ++i) { int x, y, z; cin >> x >> y >> z; int k = z / 2; int odd = z & 1; Point p; p.x = 3 * x + SX[k]; p.y = 3 * y + SY[k]; p.ori = static_cast<unsigned char>(k & 1); int incidence = (k + odd) % 3; p.label = static_cast<unsigned char>((2 * incidence) % 3); p.group = static_cast<unsigned char>(p.ori * 3 + p.label); pts.push_back(p); } cout << solveTest(pts) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; struct Point { int x, y, p; }; static inline ll hexDist(ll x, ll y) { return max({llabs(x), llabs(y), llabs(x + y)}); } // First macro-step supported by each port. type 0 = U, type 1 = D. static const int STEPS[2][3][2][2] = { { {{0,-1},{1,-1}}, {{0,1},{1,0}}, {{-1,1},{-1,0}} }, { {{0,1},{-1,1}}, {{0,-1},{-1,0}}, {{1,-1},{1,0}} } }; static inline int badPort(int type, int port, ll dx, ll dy) { ll h = hexDist(dx, dy); for (int i = 0; i < 2; ++i) { ll nx = dx - STEPS[type][port][i][0]; ll ny = dy - STEPS[type][port][i][1]; if (hexDist(nx, ny) == h - 1) return 0; } return 1; } // Distance between two flags on the same honeycomb sublattice. static int sameDistance(int type, ll dx, ll dy, int sp, int tp) { if (dx == 0 && dy == 0) return sp == tp ? 0 : 1; ll h = hexDist(dx, dy); return int(4*h - 1 + badPort(type, sp, dx, dy) + badPort(type, tp, -dx, -dy)); } // Distance from U(sp) to D(tp), where delta = D.coordinates - U.coordinates. static int crossDistance(ll dx, ll dy, int sp, int tp) { ll vx[3] = {dx, dx, dx + 1}; ll vy[3] = {dy + 1, dy, dy}; ll h[3]; ll best = LLONG_MAX; for (int j = 0; j < 3; ++j) { h[j] = hexDist(vx[j], vy[j]); best = min(best, h[j]); } int ans = INT_MAX; for (int j = 0; j < 3; ++j) if (h[j] == best) { int startCost; if (best == 0) startCost = (sp != j); else startCost = badPort(0, sp, vx[j], vy[j]); int cur = int(4*best + 1 + startCost + (tp != j)); ans = min(ans, cur); } return ans; } struct Form { int ax, ay; ll c; inline ll lin(const Point& p) const { return ll(ax)*p.x + ll(ay)*p.y; } }; struct Region { Form u, v; bool zu, zv; // true: form == 0, false: form > 0 int rx, ry; // a representative delta int alpha, beta; // distance = alpha*dx + beta*dy + constant int C[3][3]; }; static vector<Region> makeSameRegions(int type) { vector<Region> r; auto add = [&](Form u, Form v, bool zu, bool zv, int rx, int ry, int hx, int hy) { Region a{u,v,zu,zv,rx,ry,4*hx,4*hy,{}}; r.push_back(a); }; add({1,0,0},{0,1,0},0,0, 2,3, 1,1); add({1,0,0},{0,1,0},0,1, 2,0, 1,0); add({-1,0,0},{1,1,0},0,0, -1,2, 0,1); add({0,1,0},{1,0,0},0,1, 0,2, 0,1); add({0,-1,0},{1,1,0},0,0, 2,-1, 1,0); add({-1,0,0},{1,1,0},0,1, -2,2, 0,1); add({-1,0,0},{0,-1,0},0,0, -2,-3, -1,-1); add({-1,0,0},{0,1,0},0,1, -2,0, -1,0); add({1,0,0},{-1,-1,0},0,0, 1,-2, 0,-1); add({0,-1,0},{1,0,0},0,1, 0,-2, 0,-1); add({0,1,0},{-1,-1,0},0,0, -2,1, -1,0); add({1,0,0},{1,1,0},0,1, 2,-2, 1,0); add({1,0,0},{0,1,0},1,1, 0,0, 0,0); for (auto& a : r) { for (int s = 0; s < 3; ++s) for (int t = 0; t < 3; ++t) { int d = sameDistance(type, a.rx, a.ry, s, t); a.C[s][t] = d - a.alpha*a.rx - a.beta*a.ry; } } return r; } static vector<Region> makeCrossRegions() { vector<Region> r; auto add = [&](Form u, Form v, bool zu, bool zv, int rx, int ry, int alpha, int beta) { r.push_back(Region{u,v,zu,zv,rx,ry,alpha,beta,{}}); }; // A: four subregions. add({1,0,0},{0,1,0},0,0, 2,3, 4,4); add({1,0,0},{0,1,0},0,1, 2,0, 4,4); add({1,0,0},{0,1,0},1,0, 0,2, 4,4); add({1,0,0},{0,1,0},1,1, 0,0, 4,4); // B. add({-1,-1,-1},{0,1,0},0,0, -4,1, -4,0); add({-1,-1,-1},{0,1,0},0,1, -3,0, -4,0); // C. add({-1,0,-1},{1,1,1},0,0, -3,3, 0,4); add({-1,0,-1},{1,1,1},0,1, -3,2, 0,4); add({-1,0,-1},{1,1,1},1,0, -1,2, 0,4); add({-1,0,-1},{1,1,1},1,1, -1,0, 0,4); // D. add({1,1,1},{0,-1,-1},0,0, 3,-2, 4,0); add({1,1,1},{0,-1,-1},0,1, 2,-1, 4,0); // E. add({1,0,0},{-1,-1,-1},0,0, 1,-4, 0,-4); add({1,0,0},{-1,-1,-1},0,1, 2,-3, 0,-4); add({1,0,0},{-1,-1,-1},1,0, 0,-3, 0,-4); add({1,0,0},{-1,-1,-1},1,1, 0,-1, 0,-4); // F. add({-1,0,-1},{0,-1,-1},0,0, -3,-4, -4,-4); add({-1,0,-1},{0,-1,-1},1,0, -1,-3, -4,-4); add({-1,0,-1},{0,-1,-1},0,1, -3,-1, -4,-4); add({-1,0,-1},{0,-1,-1},1,1, -1,-1, -4,-4); for (auto& a : r) { for (int s = 0; s < 3; ++s) for (int t = 0; t < 3; ++t) { int d = crossDistance(a.rx, a.ry, s, t); a.C[s][t] = d - a.alpha*a.rx - a.beta*a.ry; } } return r; } struct Agg { ll cnt = 0, sx = 0, sy = 0; ll cp[3] = {0,0,0}; }; static inline Agg operator+(const Agg& a, const Agg& b) { Agg r; r.cnt = a.cnt + b.cnt; r.sx = a.sx + b.sx; r.sy = a.sy + b.sy; for (int i = 0; i < 3; ++i) r.cp[i] = a.cp[i] + b.cp[i]; return r; } static inline Agg operator-(const Agg& a, const Agg& b) { Agg r; r.cnt = a.cnt - b.cnt; r.sx = a.sx - b.sx; r.sy = a.sy - b.sy; for (int i = 0; i < 3; ++i) r.cp[i] = a.cp[i] - b.cp[i]; return r; } static inline ll contribution(const Point& p, const Region& reg, const Agg& a) { ll sdx = a.sx - a.cnt * ll(p.x); ll sdy = a.sy - a.cnt * ll(p.y); ll res = reg.alpha * sdx + reg.beta * sdy; for (int t = 0; t < 3; ++t) res += a.cp[t] * ll(reg.C[p.p][t]); return res; } struct Fenwick { int n = 0; vector<Agg> bit; Fenwick() {} explicit Fenwick(int n_) : n(n_), bit(n_+1) {} void add(int i, const Agg& a) { for (++i; i <= n; i += i & -i) bit[i] = bit[i] + a; } Agg sum(int i) const { Agg r; for (; i > 0; i -= i & -i) r = r + bit[i]; return r; } }; static ll processTwoDimensional(const vector<Point>& src, const vector<Point>& dst, const Region& reg) { int n = (int)dst.size(); struct DEntry { ll u, v; int id; }; struct Query { ll u, v; int id; }; vector<DEntry> de; vector<Query> qs; de.reserve(n); qs.reserve(src.size()); vector<ll> vs; vs.reserve(n); for (int i = 0; i < n; ++i) { ll u = reg.u.lin(dst[i]); ll v = reg.v.lin(dst[i]); de.push_back({u,v,i}); vs.push_back(v); } for (int i = 0; i < (int)src.size(); ++i) { qs.push_back({reg.u.lin(src[i]) - reg.u.c, reg.v.lin(src[i]) - reg.v.c, i}); } sort(de.begin(), de.end(), [](const DEntry& a, const DEntry& b) { return a.u > b.u; }); sort(qs.begin(), qs.end(), [](const Query& a, const Query& b) { return a.u > b.u; }); sort(vs.begin(), vs.end()); vs.erase(unique(vs.begin(), vs.end()), vs.end()); Fenwick fw((int)vs.size()); int at = 0; ll answer = 0; for (const Query& q : qs) { while (at < n && de[at].u > q.u) { const Point& p = dst[de[at].id]; int pos = int(lower_bound(vs.begin(), vs.end(), de[at].v) - vs.begin()); Agg a; a.cnt = 1; a.sx = p.x; a.sy = p.y; a.cp[p.p] = 1; fw.add(pos, a); ++at; } int pos = int(upper_bound(vs.begin(), vs.end(), q.v) - vs.begin()); Agg a = fw.sum((int)vs.size()) - fw.sum(pos); if (a.cnt) answer += contribution(src[q.id], reg, a); } return answer; } static ll processOneDimensional(const vector<Point>& src, const vector<Point>& dst, const Region& reg, bool firstIsPositive) { const Form& posF = firstIsPositive ? reg.u : reg.v; const Form& eqF = firstIsPositive ? reg.v : reg.u; struct Entry { ll key, pos; int id; }; struct Query { ll key, pos; int id; }; vector<Entry> e; vector<Query> q; e.reserve(dst.size()); q.reserve(src.size()); for (int i = 0; i < (int)dst.size(); ++i) e.push_back({eqF.lin(dst[i]), posF.lin(dst[i]), i}); for (int i = 0; i < (int)src.size(); ++i) q.push_back({eqF.lin(src[i]) - eqF.c, posF.lin(src[i]) - posF.c, i}); sort(e.begin(), e.end(), [](const Entry& a, const Entry& b) { if (a.key != b.key) return a.key < b.key; return a.pos < b.pos; }); sort(q.begin(), q.end(), [](const Query& a, const Query& b) { return a.key < b.key; }); vector<Agg> suffix(e.size()+1); size_t ei = 0, qi = 0; ll answer = 0; while (qi < q.size()) { ll key = q[qi].key; size_t qend = qi; while (qend < q.size() && q[qend].key == key) ++qend; while (ei < e.size() && e[ei].key < key) ++ei; if (ei == e.size()) break; if (e[ei].key != key) { qi = qend; continue; } size_t er = ei; while (er < e.size() && e[er].key == key) ++er; suffix[er] = Agg(); for (size_t i = er; i-- > ei; ) { const Point& p = dst[e[i].id]; Agg a; a.cnt = 1; a.sx = p.x; a.sy = p.y; a.cp[p.p] = 1; suffix[i] = suffix[i+1] + a; } for (size_t j = qi; j < qend; ++j) { size_t l = ei, r = er; while (l < r) { size_t m = (l+r)/2; if (e[m].pos > q[j].pos) r = m; else l = m+1; } const Agg& a = suffix[l]; if (a.cnt) answer += contribution(src[q[j].id], reg, a); } ei = er; qi = qend; } return answer; } static ll processZeroDimensional(const vector<Point>& src, const vector<Point>& dst, const Region& reg) { map<pair<ll,ll>, Agg> mp; for (const Point& p : dst) { Agg a; a.cnt = 1; a.sx = p.x; a.sy = p.y; a.cp[p.p] = 1; mp[{reg.u.lin(p), reg.v.lin(p)}] = mp[{reg.u.lin(p), reg.v.lin(p)}] + a; } ll answer = 0; for (const Point& p : src) { auto it = mp.find({reg.u.lin(p)-reg.u.c, reg.v.lin(p)-reg.v.c}); if (it != mp.end()) answer += contribution(p, reg, it->second); } return answer; } static ll processRegions(const vector<Point>& src, const vector<Point>& dst, const vector<Region>& regions) { if (src.empty() || dst.empty()) return 0; ll ans = 0; for (const Region& r : regions) { if (!r.zu && !r.zv) ans += processTwoDimensional(src, dst, r); else if (!r.zu && r.zv) ans += processOneDimensional(src, dst, r, true); else if (r.zu && !r.zv) ans += processOneDimensional(src, dst, r, false); else ans += processZeroDimensional(src, dst, r); } return ans; } static Point decodePoint(int x, int y, int z) { int k = z/2; bool odd = z&1; Point p{}; if (k == 0) { p = {x,y,odd?2:0}; } else if (k == 1) { p = {x-1,y,odd?1:2}; } else if (k == 2) { p = {x-1,y,odd?0:1}; } else if (k == 3) { p = {x-1,y-1,odd?2:0}; } else if (k == 4) { p = {x,y-1,odd?1:2}; } else { p = {x,y-1,odd?0:1}; } return p; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); vector<Region> sameU = makeSameRegions(0); vector<Region> sameD = makeSameRegions(1); vector<Region> crossUD = makeCrossRegions(); int T; cin >> T; while (T--) { int N; cin >> N; vector<Point> U, D; vector<pair<Point,int>> all; all.reserve(N); for (int i = 0; i < N; ++i) { int x,y,z; cin >> x >> y >> z; int k = z/2; bool isD = (k == 1 || k == 3 || k == 5); Point p = decodePoint(x,y,z); if (isD) { D.push_back(p); all.push_back({p,1}); } else { U.push_back(p); all.push_back({p,0}); } } if (N <= 128) { ll ans = 0; for (int i = 0; i < N; ++i) { for (int j = i+1; j < N; ++j) { if (all[i].second == all[j].second) { ans += sameDistance(all[i].second, ll(all[j].first.x)-all[i].first.x, ll(all[j].first.y)-all[i].first.y, all[i].first.p, all[j].first.p); } else { const Point* u = &all[i].first; const Point* d = &all[j].first; if (all[i].second == 1) swap(u,d); ans += crossDistance(ll(d->x)-u->x, ll(d->y)-u->y, u->p, d->p); } } } cout << ans << '\n'; continue; } ll same = 0; same += processRegions(U,U,sameU); same += processRegions(D,D,sameD); ll cross = processRegions(U,D,crossUD); cout << same/2 + cross << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; struct Face { long long c[3]; int p; int s; }; struct Group { long long c0, c1, c2; int p; int s; long long cnt; }; static bool cmpGroup(const Group& a, const Group& b) { if (a.c0 != b.c0) return a.c0 < b.c0; if (a.c1 != b.c1) return a.c1 < b.c1; if (a.c2 != b.c2) return a.c2 < b.c2; return a.p < b.p; } static inline long long getC(const Group& g, int p) { if (p == 0) return g.c0; if (p == 1) return g.c1; return g.c2; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; vector<Face> faces; faces.reserve(N); for (int i = 0; i < N; ++i) { long long x, y; int z; cin >> x >> y >> z; int k = z / 2; int e = z % 2; bool isD; long long lx, ly; int p; if (k == 0) { isD = false; lx = x; ly = y; p = (e == 0 ? 0 : 1); } else if (k == 1) { isD = true; lx = x - 1; ly = y; p = (e == 0 ? 1 : 2); } else if (k == 2) { isD = false; lx = x - 1; ly = y; p = (e == 0 ? 2 : 0); } else if (k == 3) { isD = true; lx = x - 1; ly = y - 1; p = (e == 0 ? 0 : 1); } else if (k == 4) { isD = false; lx = x; ly = y - 1; p = (e == 0 ? 1 : 2); } else { // k == 5 isD = true; lx = x; ly = y - 1; p = (e == 0 ? 2 : 0); } long long c0 = -ly; long long c1 = -lx; long long c2; int s; if (!isD) { c2 = lx + ly; s = 0; } else { c2 = 1 + lx + ly; s = 1; } faces.push_back({{c0, c1, c2}, p, s}); } long long U = 0; long long A = 0; for (int coord = 0; coord < 3; ++coord) { vector<long long> arr(N); for (int i = 0; i < N; ++i) { arr[i] = faces[i].c[coord]; } sort(arr.begin(), arr.end()); long long pref = 0; for (int i = 0; i < N; ++i) { U += arr[i] * (long long)i - pref; pref += arr[i]; } for (int i = 0; i < N; ++i) { if (faces[i].p != coord) continue; long long val = faces[i].c[coord]; if (faces[i].s == 0) { int greater = N - int(upper_bound(arr.begin(), arr.end(), val) - arr.begin()); A += greater; } else { int less = int(lower_bound(arr.begin(), arr.end(), val) - arr.begin()); A += less; } } } vector<Group> temp; temp.reserve(N); for (const Face& f : faces) { temp.push_back({f.c[0], f.c[1], f.c[2], f.p, f.s, 1}); } sort(temp.begin(), temp.end(), cmpGroup); vector<Group> groups; groups.reserve(N); for (int i = 0; i < N; ) { int j = i; while (j < N && temp[j].c0 == temp[i].c0 && temp[j].c1 == temp[i].c1 && temp[j].c2 == temp[i].c2 && temp[j].p == temp[i].p) { ++j; } Group g = temp[i]; g.cnt = j - i; groups.push_back(g); i = j; } long long sum_cp_sq = 0; for (const Group& g : groups) { sum_cp_sq += g.cnt * g.cnt; } long long Adj = 0; for (const Group& g : groups) { long long c0 = g.c0; long long c1 = g.c1; long long c2 = g.c2; int p = g.p; if (g.s == 0) { if (p == 0) ++c0; else if (p == 1) ++c1; else ++c2; } else { if (p == 0) --c0; else if (p == 1) --c1; else --c2; } Group key{c0, c1, c2, p, 0, 0}; auto it = lower_bound(groups.begin(), groups.end(), key, cmpGroup); if (it != groups.end() && it->c0 == c0 && it->c1 == c1 && it->c2 == c2 && it->p == p) { Adj += g.cnt * it->cnt; } } vector<pair<long long, long long>> ev[2][3]; for (const Group& g : groups) { long long val = getC(g, g.p); ev[g.s][g.p].push_back({val, g.cnt}); } vector<pair<long long, long long>> ecomp[2][3]; for (int s = 0; s < 2; ++s) { for (int p = 0; p < 3; ++p) { auto& v = ev[s][p]; sort(v.begin(), v.end()); vector<pair<long long, long long>> comp; for (auto [val, cnt] : v) { if (comp.empty() || comp.back().first != val) { comp.push_back({val, cnt}); } else { comp.back().second += cnt; } } ecomp[s][p] = move(comp); } } long long E = 0; for (const Group& g : groups) { int p = g.p; int s = g.s; long long val = getC(g, p); long long target = val + (s == 0 ? 1LL : -1LL); int s2 = 1 - s; auto& vec = ecomp[s2][p]; auto it = lower_bound( vec.begin(), vec.end(), make_pair(target, (long long)-4e18) ); if (it != vec.end() && it->first == target) { E += g.cnt * it->second; } } long long total_ordered = 4LL * U + 1LL * N * N - sum_cp_sq - 2LL * A + E - Adj; long long answer = total_ordered / 2; cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; struct Key { ll x, y, z; bool operator==(Key const& o) const { return x == o.x && y == o.y && z == o.z; } }; struct Hash { static uint64_t splitmix64(uint64_t x) { x += 0x9e3779b97f4a7c15ULL; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL; x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL; return x ^ (x >> 31); } size_t operator()(Key const& k) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); uint64_t h = 0; h ^= splitmix64((uint64_t)k.x + FIXED_RANDOM); h ^= splitmix64((uint64_t)k.y + FIXED_RANDOM); h ^= splitmix64((uint64_t)k.z + FIXED_RANDOM); return (size_t)h; } }; struct Center { ll coord[3]; int type; // 0: U (sum = 0), 1: D (sum = -1) ll total; ll side[3]; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; const ll vx[6] = {1, 0, -1, -1, 0, 1}; const ll vy[6] = {0, 1, 1, 0, -1, -1}; while (T--) { int N; cin >> N; vector<Center> centers; centers.reserve(N); unordered_map<Key, int, Hash> mp; mp.reserve((size_t)N * 2 + 10); mp.max_load_factor(0.7); for (int i = 0; i < N; ++i) { ll x, y; int z; cin >> x >> y >> z; ll Tx, Ty; int d; if (z % 2 == 0) { int k = z / 2; Tx = x; Ty = y; d = k % 6; } else { int k = z / 2; int id = (k + 1) % 6; Tx = x + vx[id]; Ty = y + vy[id]; d = (k + 4) % 6; } ll ci, cj; int side; if (d % 2 == 0) { if (d == 0) { ci = Tx; cj = Ty; } else if (d == 2) { ci = Tx - 1; cj = Ty; } else { // d == 4 ci = Tx; cj = Ty - 1; } side = (d / 2 + 1) % 3; } else { if (d == 1) { ci = Tx - 1; cj = Ty; } else if (d == 3) { ci = Tx - 1; cj = Ty - 1; } else { // d == 5 ci = Tx; cj = Ty - 1; } side = (d - 1) / 2; } ll X = ci; ll Y = cj; ll Z; int type; if (d % 2 == 0) { Z = -ci - cj; type = 0; } else { Z = -ci - cj - 1; type = 1; } Key key{X, Y, Z}; auto it = mp.find(key); int id; if (it == mp.end()) { id = (int)centers.size(); Center C; C.coord[0] = X; C.coord[1] = Y; C.coord[2] = Z; C.type = type; C.total = 0; C.side[0] = C.side[1] = C.side[2] = 0; centers.push_back(C); mp[key] = id; } else { id = it->second; } centers[id].total++; centers[id].side[side]++; } int M = (int)centers.size(); // Pairs inside the same center. ll sameCenterAnswer = 0; for (const auto& C : centers) { ll totalPairs = C.total * (C.total - 1) / 2; ll sameSidePairs = 0; for (int i = 0; i < 3; ++i) { sameSidePairs += C.side[i] * (C.side[i] - 1) / 2; } sameCenterAnswer += totalPairs - sameSidePairs; } // Sum of honeycomb distances between centers. ll sumDist = 0; for (int ci = 0; ci < 3; ++ci) { vector<int> ord(M); iota(ord.begin(), ord.end(), 0); sort(ord.begin(), ord.end(), [&](int a, int b) { return centers[a].coord[ci] < centers[b].coord[ci]; }); ll prefW = 0; ll prefVal = 0; for (int id : ord) { ll x = centers[id].coord[ci]; ll w = centers[id].total; sumDist += w * (prefW * x - prefVal); prefW += w; prefVal += w * x; } } ll totalPairsAll = (ll)N * (N - 1) / 2; ll sameCenterPairs = 0; for (const auto& C : centers) { sameCenterPairs += C.total * (C.total - 1) / 2; } ll distinctCenterPairs = totalPairsAll - sameCenterPairs; ll mainTerm = 2 * sumDist - distinctCenterPairs; // Base penalty S. ll S = 0; for (int ci = 0; ci < 3; ++ci) { vector<int> ord(M); iota(ord.begin(), ord.end(), 0); sort(ord.begin(), ord.end(), [&](int a, int b) { return centers[a].coord[ci] < centers[b].coord[ci]; }); int p = 0; ll prefixLess = 0; while (p < M) { int q = p; ll val = centers[ord[p]].coord[ci]; ll groupWeight = 0; while (q < M && centers[ord[q]].coord[ci] == val) { groupWeight += centers[ord[q]].total; ++q; } ll leWeight = prefixLess + groupWeight; for (int k = p; k < q; ++k) { int id = ord[k]; ll good; if (centers[id].type == 0) { // U: first edge is good iff other coordinate is smaller. good = prefixLess; } else { // D: first edge is good iff other coordinate is larger. good = N - leWeight; } ll bad = (N - centers[id].total) - good; S += centers[id].side[ci] * bad; } prefixLess = leWeight; p = q; } } // Conflict correction when first and last good edges use the same unique move. ll conflict = 0; for (int ci = 0; ci < 3; ++ci) { unordered_map<ll, ll> mapD; mapD.reserve((size_t)M * 2 + 10); mapD.max_load_factor(0.7); for (const auto& C : centers) { if (C.type == 1) { mapD[C.coord[ci]] += C.side[ci]; } } for (const auto& C : centers) { if (C.type != 0) continue; ll val = C.coord[ci]; auto it = mapD.find(val - 1); if (it != mapD.end()) { conflict += C.side[ci] * it->second; } // Remove the adjacent pair (distance 1), where no conflict occurs. if (C.side[ci] != 0) { Key nb{C.coord[0], C.coord[1], C.coord[2]}; if (ci == 0) --nb.x; else if (ci == 1) --nb.y; else --nb.z; auto it2 = mp.find(nb); if (it2 != mp.end()) { int did = it2->second; if (centers[did].type == 1) { conflict -= C.side[ci] * centers[did].side[ci]; } } } } } ll answer = sameCenterAnswer + mainTerm + S + conflict; cout << answer << '\n'; } return 0; }
// I was unable to derive the complete efficient solution within the time. // This is a placeholder program. It will not pass the full test suite. #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; for (int i = 0; i < N; ++i) { int x, y, z; cin >> x >> y >> z; } cout << 0 << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct Point { array<int64, 3> c; int type; // 0 = upward large triangle, 1 = downward large triangle int side; // 0, 1, 2: global side type }; Point make_point(int64 x, int64 y, int z) { bool up; int64 mx, my; int side; switch (z) { case 0: up = true; mx = x; my = y; side = 1; break; case 1: up = true; mx = x; my = y; side = 2; break; case 2: up = false; mx = x - 1; my = y; side = 2; break; case 3: up = false; mx = x - 1; my = y; side = 0; break; case 4: up = true; mx = x - 1; my = y; side = 0; break; case 5: up = true; mx = x - 1; my = y; side = 1; break; case 6: up = false; mx = x - 1; my = y - 1; side = 1; break; case 7: up = false; mx = x - 1; my = y - 1; side = 2; break; case 8: up = true; mx = x; my = y - 1; side = 2; break; case 9: up = true; mx = x; my = y - 1; side = 0; break; case 10: up = false; mx = x; my = y - 1; side = 0; break; default: up = false; mx = x; my = y - 1; side = 1; break; } Point p; p.type = up ? 0 : 1; p.side = side; if (up) { p.c = {mx + my, -my, -mx}; } else { p.c = {mx + my + 1, -my, -mx}; } return p; } // Both vectors are sorted inside the function. // Counts pairs (a,b) such that b = a + 1. int64 count_one_apart(vector<int64>& a, vector<int64>& b) { sort(a.begin(), a.end()); sort(b.begin(), b.end()); size_t i = 0, j = 0; int64 result = 0; while (i < a.size()) { int64 target = a[i] + 1; size_t ni = i + 1; while (ni < a.size() && a[ni] == a[i]) ++ni; while (j < b.size() && b[j] < target) ++j; if (j < b.size() && b[j] == target) { size_t nj = j + 1; while (nj < b.size() && b[nj] == target) ++nj; result += int64(ni - i) * int64(nj - j); } i = ni; } return result; } // Counts pairs of keys (a,b) and (a+1,b). int64 count_adjacent_keys(vector<pair<int64, int64>>& a, vector<pair<int64, int64>>& b) { sort(a.begin(), a.end()); sort(b.begin(), b.end()); size_t i = 0; int64 result = 0; while (i < a.size()) { pair<int64, int64> target = {a[i].first + 1, a[i].second}; size_t ni = i + 1; while (ni < a.size() && a[ni] == a[i]) ++ni; auto it = lower_bound(b.begin(), b.end(), target); if (it != b.end() && *it == target) { size_t nj = it + 1; while (nj < b.end() && b[nj] == target) ++nj; result += int64(ni - i) * int64(nj - it); } i = ni; } return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; vector<Point> points(N); array<vector<int64>, 3> values; for (auto& v : values) v.resize(N); for (int i = 0; i < N; ++i) { int64 x, y; int z; cin >> x >> y >> z; points[i] = make_point(x, y, z); for (int r = 0; r < 3; ++r) { values[r][i] = points[i].c[r]; } } for (auto& v : values) sort(v.begin(), v.end()); // L = sum over unordered pairs of the L1 distance between // the coordinates of their large triangles. int64 L = 0; for (int r = 0; r < 3; ++r) { for (int i = 0; i < N; ++i) { L += values[r][i] * (2LL * i - N + 1); } } // Q = sum over ordered pairs of sigma(i,j). int64 Q = 0; for (const Point& p : points) { int r = p.side; const auto& v = values[r]; if (p.type == 0) { // Upward triangle: sigma(i,j) iff c[j][side_i] > c[i][side_i]. Q += int64(v.end() - upper_bound(v.begin(), v.end(), p.c[r])); } else { // Downward triangle: sigma(i,j) iff c[j][side_i] < c[i][side_i]. Q += int64(lower_bound(v.begin(), v.end(), p.c[r]) - v.begin()); } } // Number of pairs representing exactly the same small region. vector<array<int64, 5>> keys; keys.reserve(N); for (const Point& p : points) { keys.push_back({p.c[0], p.c[1], p.c[2], int64(p.side), int64(p.type)}); } sort(keys.begin(), keys.end()); int64 duplicate_pairs = 0; for (int i = 0; i < N; ) { int j = i + 1; while (j < N && keys[j] == keys[i]) ++j; int64 cnt = j - i; duplicate_pairs += cnt * (cnt - 1) / 2; i = j; } // Count the exceptional endpoint-conflict pairs. int64 exceptional_pairs = 0; for (int r = 0; r < 3; ++r) { int q = (r + 1) % 3; vector<int64> up_values, down_values; vector<pair<int64, int64>> up_keys, down_keys; for (const Point& p : points) { if (p.side != r) continue; if (p.type == 0) { up_values.push_back(p.c[r]); up_keys.emplace_back(p.c[r], p.c[q]); } else { down_values.push_back(p.c[r]); down_keys.emplace_back(p.c[r], p.c[q]); } } // All pairs with down.c[r] = up.c[r] + 1. int64 total = count_one_apart(up_values, down_values); // Exclude adjacent large triangles: those also have equal q-coordinate. int64 adjacent = count_adjacent_keys(up_keys, down_keys); exceptional_pairs += total - adjacent; } int64 answer = 2 * L + 1LL * N * (N - 1) / 2 - Q - duplicate_pairs + exceptional_pairs; cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct Point { array<int64, 3> c; int mark; // Coordinate of the original edge containing the region. }; struct Fenwick { int n; vector<int> tree; explicit Fenwick(int n = 0) : n(n), tree(n + 1, 0) {} void add(int pos) { for (++pos; pos <= n; pos += pos & -pos) { ++tree[pos]; } } int prefixSum(int count) const { int result = 0; for (int i = count; i > 0; i -= i & -i) { result += tree[i]; } return result; } }; // Counts pairs (u,d) satisfying: // c[u][a] < c[d][a] and c[u][b] > c[d][b]. int64 countPattern(const vector<Point>& U, const vector<Point>& D, const vector<int>& us, const vector<int>& ds, int a, int b) { if (us.empty() || ds.empty()) return 0; // Small groups are faster to handle directly. if (1ULL * us.size() * ds.size() <= 256) { int64 result = 0; for (int u : us) { for (int d : ds) { if (U[u].c[a] < D[d].c[a] && U[u].c[b] > D[d].c[b]) { ++result; } } } return result; } vector<int64> values; values.reserve(us.size()); for (int u : us) values.push_back(U[u].c[a]); sort(values.begin(), values.end()); values.erase(unique(values.begin(), values.end()), values.end()); vector<int> orderU = us; vector<int> orderD = ds; sort(orderU.begin(), orderU.end(), [&](int x, int y) { return U[x].c[b] > U[y].c[b]; }); sort(orderD.begin(), orderD.end(), [&](int x, int y) { return D[x].c[b] > D[y].c[b]; }); Fenwick fw((int)values.size()); int ptr = 0; int64 result = 0; for (int d : orderD) { while (ptr < (int)orderU.size() && U[orderU[ptr]].c[b] > D[d].c[b]) { int u = orderU[ptr++]; int pos = lower_bound(values.begin(), values.end(), U[u].c[a]) - values.begin(); fw.add(pos); } int pos = lower_bound(values.begin(), values.end(), D[d].c[a]) - values.begin(); result += fw.prefixSum(pos); } return result; } // Counts the exceptional opposite-orientation pairs described below. int64 countConflicts(const vector<Point>& U, const vector<Point>& D) { int64 result = 0; for (int k = 0; k < 3; ++k) { vector<pair<int64, int>> ue, de; ue.reserve(U.size()); de.reserve(D.size()); for (int i = 0; i < (int)U.size(); ++i) { if (U[i].mark == k + 1) { ue.emplace_back(U[i].c[k] - 1, i); } } for (int i = 0; i < (int)D.size(); ++i) { if (D[i].mark == k + 1) { de.emplace_back(D[i].c[i], i); } } sort(ue.begin(), ue.end()); sort(de.begin(), de.end()); int i = 0, j = 0; while (i < (int)ue.size() && j < (int)de.size()) { if (ue[i].first < de[j].first) { ++i; } else if (ue[i].first > de[j].first) { ++j; } else { int64 key = ue[i].first; vector<int> us, ds; while (i < (int)ue.size() && ue[i].first == key) { us.push_back(ue[i].second); ++i; } while (j < (int)de.size() && de[j].first == key) { ds.push_back(de[j].second); ++j; } int a = (k + 1) % 3; int b = (k + 2) % 3; result += countPattern(U, D, us, ds, a, b); result += countPattern(U, D, us, ds, b, a); } } } return result; } int64 sumAbsolutePairs(const vector<int64>& sortedValues) { int64 result = 0; int64 prefix = 0; for (int i = 0; i < (int)sortedValues.size(); ++i) { result += sortedValues[i] * i - prefix; prefix += sortedValues[i]; } return result; } int64 sumAbsoluteCross(const vector<int64>& A, const vector<int64>& B) { vector<int64> prefix(B.size() + 1, 0); for (int i = 0; i < (int)B.size(); ++i) { prefix[i + 1] = prefix[i] + B[i]; } int64 totalB = prefix.back(); int64 result = 0; for (int64 a : A) { int less = lower_bound(B.begin(), B.end(), a) - B.begin(); int lessOrEqual = upper_bound(B.begin(), B.end(), a) - B.begin(); int greater = (int)B.size() - lessOrEqual; int64 sumLess = prefix[less]; int64 sumGreater = totalB - prefix[lessOrEqual]; result += a * less - sumLess; result += sumGreater - a * greater; } return result; } int64 countIdentical(const vector<Point>& points) { vector<array<int64, 4>> keys; keys.reserve(points.size()); for (const Point& p : points) { keys.push_back({p.c[0], p.c[1], p.c[2], p.mark}); } sort(keys.begin(), keys.end()); int64 result = 0; for (int i = 0; i < (int)keys.size();) { int j = i + 1; while (j < (int)keys.size() && keys[j] == keys[i]) ++j; int64 count = j - i; result += count * (count - 1) / 2; i = j; } return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; vector<Point> U, D; U.reserve(N); D.reserve(N); for (int i = 0; i < N; ++i) { int x, y, z; cin >> x >> y >> z; bool isU; int64 i0, j0; int family; switch (z) { case 0: isU = true; i0 = x; j0 = y; family = 0; break; case 1: isU = true; i0 = x; j0 = y; family = 1; break; case 2: isU = false; i0 = x - 1; j0 = y; family = 1; break; case 3: isU = false; i0 = x - 1; j0 = y; family = 2; break; case 4: isU = true; i0 = x - 1; j0 = y; family = 2; break; case 5: isU = true; i0 = x - 1; j0 = y; family = 0; break; case 6: isU = false; i0 = x - 1; j0 = y - 1; family = 0; break; case 7: isU = false; i0 = x - 1; j0 = y - 1; family = 1; break; case 8: isU = true; i0 = x; j0 = y - 1; family = 1; break; case 9: isU = true; i0 = x; j0 = y - 1; family = 2; break; case 10: isU = false; i0 = x; j0 = y - 1; family = 2; break; default: isU = false; i0 = x; j0 = y - 1; family = 0; break; } // Families 0,1,2 correspond to coordinates 2,1,3. int mark = (family == 0 ? 2 : (family == 1 ? 1 : 3)); Point p; p.mark = mark; if (isU) { p.c = {i0, j0, -i0 - j0}; U.push_back(p); } else { p.c = {i0, j0, -i0 - j0 - 1}; D.push_back(p); } } array<vector<int64>, 3> sortedU, sortedD; for (const Point& p : U) { for (int k = 0; k < 3; ++k) sortedU[k].push_back(p.c[k]); } for (const Point& p : D) { for (int k = 0; k < 3; ++k) sortedD[k].push_back(p.c[k]); } for (int k = 0; k < 3; ++k) { sort(sortedU[k].begin(), sortedU[k].end()); sort(sortedD[k].begin(), sortedD[k].end()); } int64 MU = 0, MD = 0, MC = 0; for (int k = 0; k < 3; ++k) { MU += sumAbsolutePairs(sortedU[k]); MD += sumAbsolutePairs(sortedD[k]); MC += sumAbsoluteCross(sortedU[k], sortedD[k]); } int64 AU = 0, AD = 0; int64 crossStart = 0, crossEnd = 0; for (const Point& p : U) { int k = p.mark - 1; AU += lower_bound(sortedU[k].begin(), sortedU[k].end(), p.c[k]) - sortedU[k].begin(); crossStart += lower_bound(sortedD[k].begin(), sortedD[k].end(), p.c[k]) - sortedD[k].begin(); } for (const Point& p : D) { int k = p.mark - 1; AD += sortedD[k].end() - upper_bound(sortedD[k].begin(), sortedD[k].end(), p.c[k]); crossEnd += sortedU[k].end() - upper_bound(sortedU[k].begin(), sortedU[k].end(), p.c[k]); } int64 identicalU = countIdentical(U); int64 identicalD = countIdentical(D); int64 conflicts = countConflicts(U, D); int64 nU = U.size(); int64 nD = D.size(); int64 answer = 0; answer += 2 * MU + nU * (nU - 1) / 2 - AU - identicalU; answer += 2 * MD + nD * (nD - 1) / 2 - AD - identicalD; answer += 2 * MC + nU * nD - crossStart - crossEnd + conflicts; cout << answer << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct Region { // kind = 0: U triangle, kind = 1: D triangle int kind; int a, b; int side; array<int64, 3> q; }; static vector<pair<int64, int64>> compress(vector<int64>& v) { sort(v.begin(), v.end()); vector<pair<int64, int64>> result; for (int64 x : v) { if (!result.empty() && result.back().first == x) { ++result.back().second; } else { result.emplace_back(x, 1); } } return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; vector<Region> regions(N); array<vector<int64>, 3> coordinates; array<vector<int64>, 3> upValues, downValues; // Keys of D regions: {a, b, side}. vector<array<int, 3>> downKeys; // Keys of all regions: {kind, a, b, side}. vector<array<int, 4>> allKeys; for (int i = 0; i < N; ++i) { int x, y, z; cin >> x >> y >> z; int k = z / 2; int parity = z & 1; Region& r = regions[i]; // The 60-degree sector containing the input direction. switch (k) { case 0: r.kind = 0; r.a = x; r.b = y; break; case 1: r.kind = 1; r.a = x - 1; r.b = y + 1; break; case 2: r.kind = 0; r.a = x - 1; r.b = y; break; case 3: r.kind = 1; r.a = x - 1; r.b = y; break; case 4: r.kind = 0; r.a = x; r.b = y - 1; break; default: r.kind = 1; r.a = x; r.b = y; break; } r.side = (k + parity) % 3; if (r.kind == 0) { r.q = {-int64(r.b), -int64(r.a), int64(r.a) + r.b}; } else { r.q = {1 - int64(r.b), -int64(r.a), int64(r.a) + r.b}; } for (int t = 0; t < 3; ++t) { coordinates[t].push_back(r.q[t]); } if (r.kind == 0) { upValues[r.side].push_back(r.q[r.side]); } else { downValues[r.side].push_back(r.q[r.side]); downKeys.push_back({r.a, r.b, r.side}); } allKeys.push_back({r.kind, r.a, r.b, r.side}); } // Sum of distances between the containing big triangles. int64 sumBigTriangleDistance = 0; for (int t = 0; t < 3; ++t) { auto& v = coordinates[t]; sort(v.begin(), v.end()); int64 prefix = 0; for (int i = 0; i < N; ++i) { sumBigTriangleDistance += v[i] * int64(i) - prefix; prefix += v[i]; } } // Sum of all endpoint mismatch contributions. int64 mismatchTotal = 0; for (const Region& r : regions) { const auto& v = coordinates[r.side]; int64 value = r.q[r.side]; if (r.kind == 0) { // U -> other: a matching first edge requires q_side(other) > value. int64 count = upper_bound(v.begin(), v.end(), value) - v.begin(); mismatchTotal += count - 1; // Exclude the point itself. } else { // D -> other: a matching first edge requires q_side(other) < value. int64 count = v.end() - lower_bound(v.begin(), v.end(), value); mismatchTotal += count - 1; // Exclude the point itself. } } // Potential conflicts: // opposite triangle kinds, equal selected side, and // q_side(D) = q_side(U) + 1. int64 rawConflicts = 0; for (int t = 0; t < 3; ++t) { auto up = compress(upValues[t]); auto down = compress(downValues[t]); size_t j = 0; for (const auto& [value, count] : up) { int64 target = value + 1; while (j < down.size() && down[j].first < target) { ++j; } if (j < down.size() && down[j].first == target) { rawConflicts += count * down[j].second; } } } // Remove the directly adjacent cases. In those cases the unique // matching edge is simultaneously the first and last edge. sort(downKeys.begin(), downKeys.end()); int64 directConflicts = 0; for (const Region& r : regions) { if (r.kind != 0) continue; array<int, 3> target; if (r.side == 0) { target = {r.a, r.b, 0}; } else if (r.side == 1) { target = {r.a - 1, r.b + 1, 1}; } else { target = {r.a, r.b + 1, 2}; } auto [lo, hi] = equal_range(downKeys.begin(), downKeys.end(), target); directConflicts += int64(hi - lo); } int64 conflicts = rawConflicts - directConflicts; // Identical big triangle + side means the same small region. // Such pairs have distance zero instead of the generic value one. sort(allKeys.begin(), allKeys.end()); int64 identicalPairs = 0; for (size_t i = 0; i < allKeys.size();) { size_t j = i + 1; while (j < allKeys.size() && allKeys[j] == allKeys[i]) { ++j; } int64 count = int64(j - i); identicalPairs += count * (count - 1) / 2; i = j; } int64 pairCount = int64(N) * (N - 1) / 2; int64 answer = 2 * sumBigTriangleDistance - pairCount + mismatchTotal + conflicts - identicalPairs; cout << answer << '\n'; } return 0; }