Point on Spiral(codeforces 279A)
Point on Spiral
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.
Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).
The first line contains two space-separated integers x and y (|x|, |y| ≤ 100).
Print a single integer, showing how many times Valera has to turn.
0 0
0
1 0
0
0 1
2
-1 -1
3
#include<iostream> #include<cstdio> #include<cmath> using namespace std; long long ans = 1, cnt=1; struct Point{ int x,y; Point(){} Point(double a, double b):x(a),y(b){} Point operator-(const Point &a)const{ return Point(x - a.x, y - a.y); } int operator^(const Point &a)const{ return x * a.y - y * a.x; } int operator*(const Point &a)const{ return x * a.x + y * a.y; } void output(){ printf("x = %d y = %d\n", x, y); } }; struct Line{ Point s,e; Line(){} Line(const Point &a, const Point &b):s(a),e(b){} Line(const Line &a){ s = a.s, e = a.e; } bool pointonseg(Point p){ return ((p-s)^(e-s)) == 0 && ((p-s)*(p-e)) <= 0; } void output(){ cout<<"s:"; s.output(); cout<<"e:"; e.output(); cout<<endl; } }; inline void add(Line &a){ if(a.s.x < a.e.x) a = Line(a.e, Point(ans, ans)); else if(a.s.y < a.e.y) a = Line(a.e, Point(-ans, ans)); else if(a.s.x > a.e.x) a = Line(a.e, Point(-ans, -ans)); else { a = Line(a.e, Point(ans + 1, -ans)); ans++; } cnt++; return; } int main(){ int a,b; Line ln(Point(0,0), Point(1,0)); scanf("%d%d",&a, &b); Point d(a,b); while(1){ if(ln.pointonseg(d)){ printf("%I64d", cnt-1); break; } add(ln); } return 0; }