Point on Spiral(codeforces 279A)

Point on Spiral

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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).

Input

The first line contains two space-separated integers x and y (|x|, |y| ≤ 100).

Output

Print a single integer, showing how many times Valera has to turn.

Examples
Input
Copy
0 0
Output
Copy
0
Input
Copy
1 0
Output
Copy
0
Input
Copy
0 1
Output
Copy
2
Input
Copy
-1 -1
Output
Copy
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;
}

 

 

posted @ 2019-10-13 14:49  Unknown_Island  阅读(189)  评论(0编辑  收藏  举报