B - Two Rings Editorial by en_translator
Let \(D\) be the distance between the centers of the two circles. Then the two circles intersect if and only if
\[|R_1 - R_2| \leq D \leq R_1 + R_2.\]
See also: 2つの円の位置関係(高校数学の美しい物語) (Japanese)
Since \(D = \sqrt{(X_1 - X_2)^2 + (Y_1 - Y_2)^2}\), the problem can be solved by evaluating the truth value of
\[|R_1 - R_2| \leq \sqrt{(X_1 - X_2)^2 + (Y_1 - Y_2)^2} \leq R_1 + R_2.\]
However, actually calculating the values above may result in a wrong answer due to precision errors. Instead, we notice that the both sides are positive and squaring both sides do not change the truth value. Thus, evaluating
\[(R_1 - R_2)^2 \leq (X_1 - X_2)^2 + (Y_1 - Y_2)^2 \leq (R_1 + R_2)^2\]
involves only integers and gives a correct verdict without an error.
The complexity is \(\mathrm{O}(1)\), which is fast enough.
- Sample code (C++)
#include <iostream>
using namespace std;
int main() {
int T;
cin >> T;
while (T--) {
long long x1, y1, r1, x2, y2, r2;
cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2;
auto sq = [](long long x) { return x * x; };
auto L = sq(r1 - r2);
auto M = sq(x1 - x2) + sq(y1 - y2);
auto R = sq(r1 + r2);
cout << (L <= M and M <= R ? "Yes" : "No") << "\n";
}
}
posted:
last update: