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是第幾圈上的座標。
然後其實可以自己畫出圖,將座標標上再找規律,如圖:

然後可以將每個圈分成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;
}



發佈了20 篇原創文章 · 獲贊 21 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章