hdu 1030 Delta-wave (C++, 0ms, explanatory comments.)

problem description http://acm.hdu.edu.cn/showproblem.php?pid=1030

#include <cstdio>
#include <cmath>
#include <algorithm>

int calPathLength(int x, int y) {
    //path length from 1 (1st line, lower) to a number in ith line is only differ by -1, 
    // 1 to 17 - 25 (5th line) is 2*(5-1)+(0 or -1)
    //path length from 3 (3rd line, upper) to a number in ith line (except first, last one)
    // is only differ by 1,   3 to 18 - 24 (5th line) is 2*(5-2)+(0 or 1)
    // if y is out of valid triangle starting from x, then plus distance with the border
    // left_border=cx, right_border=cx+(ry-rx)*2
    // if on the left, plus left_border-cy,
    // if on the right, plus cy-right_border,
    // if in the valid range, plus by 0, 1, or -1, namely (cy&1)-(cx&1)

    int rx,ry,cx,cy, tmp,res; // x is the cx-th number in row rx
    if(x>y) std::swap(x,y);

    rx=sqrt(x-1), ry=sqrt(y-1);
    cx=x-rx*rx;
    cy=y-ry*ry;
    res=(ry-rx)<<1;
    if((tmp=cx-cy)>=0) return res+tmp;
    if((tmp=cy-cx-res)>=0) return res+tmp;
    else return res+(cy&1)-(cx&1);
}

int main() {
    //freopen("input.txt","r",stdin);
    int x,y;
    while(scanf("%d%d",&x,&y)!=EOF) {
        printf("%d\n",calPathLength(x,y));
    }
    return 0;
}

thanks to http://www.acmerblog.com/hdu-1030-delta-wave-1282.html
below is an excerpt with a little modification.
求三角形内两点的最短路径,很容易证明最短的路径就是两点在三个方向的距离之和。

#include <cstdio>
#include <cmath>

int main() {
    int m,n,ai,aj,bi,bj,ak,bk;
    while (scanf("%d%d",&m,&n)!=EOF) {
        ai = sqrt(m-1);
        bi = sqrt(n-1);
        aj = (m-ai*ai-1)>>1;
        bj = (n-bi*bi-1)>>1;
        ak = ((ai+1)*(ai+1)-m)>>1;
        bk = ((bi+1)*(bi+1)-n)>>1;
        printf("%d\n",abs(ai-bi)+abs(aj-bj)+abs(ak-bk));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值