hdu 1030 Delta-wave (C++, 0ms, explanatory comments.) 分类: hdoj 2015-06-15 12:21 45人阅读 评论(0) 收藏

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
",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
",abs(ai-bi)+abs(aj-bj)+abs(ak-bk));
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。// p.s. If in any way improment can be achieved, better performance or whatever, it will be well-appreciated to let me know, thanks in advance.

原文地址:https://www.cnblogs.com/qeatzy/p/4716234.html