您的位置:首页 > 其它

hdoj 3766 Knight's Trip 【】

2015-11-07 22:41 323 查看
——计算机学院大学生程序设计竞赛(新生为主)

Knight's Trip

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 469 Accepted Submission(s): 99



Problem Description

In chess, each move of a knight consists of moving by two squares horizontally and one square vertically, or by one square horizontally and two squares vertically. A knight making one move from location (0,0) of an infinite chess board would end up at one of
the following eight locations: (1,2), (-1,2), (1,-2), (-1,-2), (2,1), (-2,1), (2,-1), (-2,-1).

Starting from location (0,0), what is the minimum number of moves required for a knight to get to some other arbitrary location (x,y)?

Input

Each line of input contains two integers x and y, each with absolute value at most one billion. The integers designate a location (x,y) on the infinite chess board. The final line contains the word END.

Output

For each location in the input, output a line containing one integer, the minimum number of moves required for a knight to move from (0,0) to (x, y).

Sample Input

1 2
2 4
END


Sample Output

1
2分析:这题刚开始一直想用bfs做,但是没有规定N,m,所以用bfs写肯定不对,不用bfs,找规律不太擅长,所以没有做出来。代码:
#include<cstdio>
#include<cstring>
int main()
{
char str[20];
while(scanf("%s",str),str[0]!='E')
{
int x=0,y,flag=1;
int k;
for(int i=0;str[i];i++)
{
if(str[i]=='-'&&i==0)
flag=-1;
else
x=x*10+str[i]-48;
}
x=x*flag;
scanf("%d",&y);
if(x<0)
x=-x;
if(y<0)
y=-y;
if(y<x)
{
k=x;x=y;
y=k;
}
if(y<=2*x)
{
if(x==1&&y==1)
printf("2\n");
else if(x==2&&y==2)
printf("4\n");
else printf("%d\n",(x+y)/3+(x+y)%3);
}
else{
int ans=x;
int cc=(y-2*x)%4;
ans+=cc;
ans+=(y-2*x-cc)/2;
if(y==1&&x==0)
ans=3;
printf("%d\n",ans);
}
}
return 0;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: