hdoj 3766 Knight's Trip 【】

 

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值