[恢]hdu 1030
2011-12-27 00:16:34
地址:http://acm.hdu.edu.cn/showproblem.php?pid=1030
题意:问图里两个数字之间最少需要多少步。
mark:注意小数在前大数在后,先算出行列,然后分奇偶。
代码:
# include <stdio.h>
# include <math.h>
int min(int a, int b){return a<b?a:b;}
int max(int a, int b){return a>b?a:b;}
int row(int n)
{
int r = sqrt(1.0*n) ;
if (r*r == n) return r ;
else return r+1 ;
}
int col(int r, int n)
{
return n-(r-1)*(r-1) ;
}
int gao(int r1, int c1, int r2, int c2)
{
int range = c1 + (r2-r1)*2 ;
if (c2 > range)
return c2-range+gao(r1, c1, r2, range) ;
if (c2 < c1)
return c1-c2+gao(r1, c1, r2, c1) ;
return (r2-r1)*2-((c2&1)==0) ;
}
int calc(int a, int b)
{
int r1 = row(a), c1 = col(r1, a) ;
int r2 = row(b), c2 = col(r2, b) ;
if ((c1&1)==0) return 1+min(gao(r1, c1-1, r2, c2),
gao(r1, c1+1, r2, c2)) ;
return gao(r1, c1, r2, c2) ;
}
int main ()
{
int a, b ;
while (~scanf ("%d %d", &a, &b))
printf("%d\n", calc(min(a,b), max(a,b))) ;
return 0 ;
}