C++ Number Of Disc Intersections
#include <vector>
long long numberOfDiscIntersections(const std::vector<int>& a)
{
long long sum = 0;
long long active = 0;
int c = static_cast<int>(a.size());
std::vector<int> start(c, 0);
std::vector<int> end(c, 0);
for (int k = 0; k < c; ++k) {
long long v = a[k];
long long key = (k < v) ? 0 : k - v;
++start[static_cast<int>(key)];
long long key2 = (static_cast<long long>(k) + v >= c) ? c - 1 : k + v;
++end[static_cast<int>(key2)];
}
for (int k = 0; k < c; ++k) {
sum += active * start[k] + (static_cast<long long>(start[k]) * (start[k] - 1)) / 2;
active += start[k] - end[k];
if (sum > 10000000) {
return -1;
}
}
return sum;
}
This sorts disc start and end points and counts active overlaps without comparing every pair directly.