Beehive UVALive - 7528

本文介绍了一种通过建立坐标系来解决六边形网格中任意两点间最短距离的方法。利用C++实现,该算法能够快速计算出任意两个六边形节点间的距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There is an infinite beehive like the one given in the figure. We consider two cells to be adjacent if andonly if they share a side. A path of length k from cell c0 to cell ck is a sequence of cells c0, c1, . . . , cksuch that ci and ci+1 are adjacent for all 0 ≤ i < k. The distance between cells i and j is the length ofthe shortest path from cell i to cell j

这里写图片描述

The cells of the beehive are indexed using positive integers as shown. The cells with larger distancefrom cell 1 are given larger indices. The indices of cells with the same distance from cell 1 increasesfrom left to right. Each positive integer is the index of exactly one cell.We want to know the distance of two cells whose indices are given.

Input

There are multiple test cases in the input. Each test case is a single line containing two space-separatedintegers i and j as the indices of two cells (1 ≤ i, j ≤ 104). The input terminates with a line containing‘0 0’ which should not be processed as a test case.

output

For each test case, output a single line containing the distance of the given cells.

Sample Input

8 4

11 12

365 365

0 0

Sample Output

2

5

0

题意:任意给你两个六边形的号问你它们之间的最短距离

思路:建立坐标系

#include <bits/stdc++.h>
using namespace std;
#define maxn 101000
int x[maxn],y[maxn];
void init()
{
       x[1] = 0,y[1] = 0;
    for(int i = 2, num = 1; num <= 11000; i++)
    {
        int px = 0 - ( i - 1);
        int py = i % 2 ? 0 : 1;
        for(int j = (i + 1) / 2; j > 0; j--)
        {
            x[++num] = px;
            y[num] = py;
            py += 2;
        }
        py--;
        px++;
        for(int j = i - 1; j >= 1; j--)
        {
            x[++num] = px++;
            y[num]  = py++;
        }
        py-= 2;;
        for(int j = i - 1; j >= 1; j--)
        {
            x[++num] = px++;
            y[num] = py--;
        }
        py--;
        px--;
        for(int j = ( i + 1)/2 - 1; j >= 1; j-- )
        {
            x[++num] = px;
            y[num] = py;
            py -= 2;
        }
    }
}
int main()
{
    int n, m;
    init();
//    for(int i = 1; i <= 20; i++)
//        printf("%d : %d %d\n",i,x[i],y[i]);
    while(~scanf("%d%d", &n, &m))
    {
        if(!n && !m)
            break;
        int dx = abs(x[n] - x[m]);
        int dy = abs(y[n] - y[m]);
        //printf("dx: %d   dy: %d\n",dx,dy);
        if(dx >= dy)
            printf("%d\n", dx);
        else printf("%d\n", dx + (dy - dx)/2);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值