Official

B - Get Closer Editorial by en_translator


Solution 1. Using the distance between the two points

Let \(d\) be the distance between point \((0,0)\) and point \((A,B)\); then the answer is \(\left( \frac{A}{d}, \frac{B}{d} \right)\).
Here, \(d=\sqrt{A^2+B^2}\).

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int x,y;
  cin >> x >> y;
  int d2=x*x+y*y;
  double d=d2;
  d=sqrt(d);
  double dx=x,dy=y;
  cout << dx/d << ' ' << dy/d << '\n';
  return 0;
}

Solution 2. Using the azimuth angle

Let \(\theta\) be the angle between “the segment connecting points \((0,0)\) and \((1,0\)” and “the segment connecting points \((0,0)\) and \((A,B)\),” then the answer is \((\cos \theta, \sin \theta)\).
This problem can be solved with atan2 function.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int x,y;
  cin >> x >> y;
  double theta=atan2((double)y,(double)x);
  cout << cos(theta) << ' ' << sin(theta) << '\n';
  return 0;
}

Notes

Be careful of formats when outputting decimals. The following sample code prints decimals as follows.

  • Line \(1\): printing the value without any specification. The number of digits in output may not be adequate enough.
  • Line \(2\): specifying to output \(12\) significant digits.
  • Line \(3\): specifying to output \(12\) digits after the decimal point.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  double x=123.456789012345678;
  cout << x << '\n';                          // 123.457
  cout << std::setprecision(12) << x << '\n'; // 123.456789012
  printf("%.12lf\n",x);                       // 123.456789012346
}

posted:
last update: