CF 338 Hexagons

Description

Ayrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined:

Ayrat is searching through the field. He started at point (0, 0) and is moving along the spiral (see second picture). Sometimes he forgets where he is now. Help Ayrat determine his location aftern moves.

Input

The only line of the input contains integer n (0 ≤ n ≤ 1018) — the number of Ayrat's moves.

Output

Print two integers x and y — current coordinates of Ayrat coordinates.

Sample Input

Input
3
Output
-2 0
Input
7
Output
3 2

这道题从数据上可以看出来是一道找规律的题,
实际上如果不看题解我也很难找到规律在哪,
首先肯定要找到输入的n是在第几圈上面的,
每圈是递增序列6 12 18 24 30 ...,所以需要用到二分
查找n是第几圈上的坐标。
然后其实可以自己画出图,将坐标标上再找规律,如图:
CF 338 Hexagons_第1张图片
然后可以将每个圈分成6+1块,因为最后一个特殊考虑,
则可以根据余数和除数求出对应的坐标,不过这个规律有点
难以找到。
#include <stdio.h>
#define LL long long
#define INF 1e9
LL binary_search ( LL l, LL r, LL k )
{
    LL mid;
    while ( l < r )
    {
        mid = ( l+r ) >> 1;
        if ( 3*mid*( mid+1 ) >= k )
            r = mid;
        else
            l = mid+1;
    }
    return l;
}
int main ( )
{
    LL n, x, y;
    scanf ( "%I64d", &n );
    if ( n == 0 )   //n=0时特殊考虑
    {
        printf ( "0 0" );
        return 0;
    }
    LL t = binary_search ( 0, INF, n ); //查询n在第几圈
    t --;   //查出来会多1
    LL mod = n-3*t*( t+1 ); //余数
    if ( mod == 0 )
        x = 2*t, y = 0;
    else
    {
        t ++;
        LL tt = mod/t;  //除以圈数就可以分成7部分(特殊部分等于6)
        mod = mod%t;
        //printf ( "%I64d %I64d %I64d\n", tt, mod, t );
        switch ( tt )
        //将每个圈分成7个部分,根据图将每部分一个个算出来
        {
        case 0 :    //根据图片结果算出坐标
            x = 2*t-mod;
            y = 2*mod;
            break ;
        case 1 :
            x = t-2*mod;
            y = 2*t;
            break ;
        case 2 :
            x = -t-mod;
            y = 2*t-2*mod;
            break ;
        case 3 :
            x = -2*t+mod;
            y = -2*mod;
            break ;
        case 4 :
            x = -t+2*mod;
            y = -2*t;
            break ;
        case 5 :
            x = t+mod;
            y = -2*t+2*mod;
            break ;
        case 6 :
            x = 2*t;
            y = 0;
            break ;
        }
    }
    printf ( "%I64d %I64d\n", x, y );
    return 0;
}


你可能感兴趣的:(CF 338 Hexagons)