hdu 1030 Delta-wave

Delta-wave

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5781    Accepted Submission(s): 2203


Problem Description
A triangle field is numbered with successive integers in the way shown on the picture below. 



The traveller needs to go from the cell with number M to the cell with number N. The traveller is able to enter the cell through cell edges only, he can not travel from cell to cell through vertices. The number of edges the traveller passes makes the length of the traveller's route. 

Write the program to determine the length of the shortest route connecting cells with numbers N and M. 
 

Input
Input contains two integer numbers M and N in the range from 1 to 1000000000 separated with space(s).
 

Output
Output should contain the length of the shortest route.
 

Sample Input
  
  
6 12
 

Sample Output
  
  
3
 

#include<iostream>
#include<algorithm>
#include<cmath>
#define MAX(x,y) ((x)>(y)?(x):(y))
#define MIN(x,y) ((x)<(y)?(x):(y))
using namespace std;
int f(int x1,int x2,int y1,int y2){//调用前须保证y1为奇数 
	if(y1<=y2&&y2<=y1+2*(x2-x1)){//(x2,y2)在(x1,y1)的左右两条斜线的内部 
		return 2*(x2-x1)-!(y2&1);//若为奇数则为相隔的行数的二倍 ,否则行数的二倍-1 
	}
	else if(y1>y2){//(x2,y2)在(x1,y1)左斜线的左侧 
		return 2*(x2-x1)+y1-y2;
	}
	else {//(x2,y2)在(x1,y1)右斜线的右侧 
		return 2*(x2-x1)+y2-y1-2*(x2-x1);
	}
}
	
int N,M;
int main(){
	int x1,x2,y1,y2,ans1,ans2,i,j,k,m,n;
	while(cin>>M>>N){
		if(M>N)swap(M,N);//使M在N上方 
		/*求出M,N的坐标*/ 
		x1=(int)(ceil(sqrt((double) M))); 
		y1=M-(x1-1)*(x1-1);
		x2=(int)(ceil(sqrt((double) N)));
		y2=N-(x2-1)*(x2-1);
		ans1=ans2=0x7fffffff;
		if(!(y1&1)){//若y1为偶数,则取两项的较小者 
			if(y1>1)ans1=f(x1,x2,y1-1,y2);
			if(y1<2*x2-1)ans2=f(x1,x2,y1+1,y2);
			cout<<MIN(ans1,ans2)+1<<endl;
		}
		else{//否则直接求值 
			cout<<f(x1,x2,y1,y2)<<endl;
		}
	}
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值