螺旋折线---第九届蓝桥杯省赛题目七

  • 题目描述

    标题:螺旋折线

如图所示的螺旋折线经过平面上所有整点恰好一次。  
对于整点(X, Y),我们定义它到原点的距离dis(X, Y)是从原点到(X, Y)的螺旋折线段的长度。  

例如dis(0, 1)=3, dis(-2, -1)=9  

给出整点坐标(X, Y),你能计算出dis(X, Y)吗?

【输入格式】
  X和Y  

  对于40%的数据,-1000 <= X, Y <= 1000  
  对于70%的数据,-100000 <= X, Y <= 100000  
  对于100%的数据, -1000000000 <= X, Y <= 1000000000  

【输出格式】
输出dis(X, Y)  


【样例输入】
  0 1

【样例输出】
  3


资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗  < 1000ms


请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。

注意:
main函数需要返回0;
只使用ANSI C/ANSI C++ 标准;
不要调用依赖于编译环境或操作系统的特殊函数。
所有依赖的函数必须明确地在源文件中 #include <xxx>
不能通过工程设置而省略常用头文件。

提交程序时,注意选择所期望的语言类型和编译器类型。

 

  • 解题代码

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
	int x = 0;
	int y = 0;
	int bound = 1;
	int target_x, target_y;
	scanf("%d%d", &target_x, &target_y);
	int step = 0;

	while((x != target_x)||(y != target_y)){//没有追到目标点。
		while(-x < bound&&(x != target_x||y != target_y)){
			x--;
			step++;
			if(x==y){//扩界
				bound++;
			}
		}
		if(x == target_x&&y == target_y) break;//追到目标点位置。

		while(y < bound&&(x != target_x||y != target_y)){
			y++;
			step++;
		}
		if(x == target_x&&y == target_y) break;//追到目标点位置。

		while(x < bound&&(x != target_x||y != target_y)){
			x++;
			step++;
		}
		if(x == target_x&&y == target_y) break;//追到目标点位置。

		while(-y < bound&&(x != target_x||y != target_y)){
			y--;
			step++;
		}
		if(x == target_x&&y == target_y) break;//追到目标点位置。
	}
	cout<<step;
	return 0;
}
  • 解题思路

    首先需要定义一个界bound,初始值为1。

    然后将螺旋线拆分成四段,这四段在图中已经被用不用颜色的箭头标注出来了。通过控制x、y的值来沿箭头方向移动,移动过程中判断是否碰到了边界bound。如果碰到了边界就要转向。当x、y为特定值时边界bound++,具体位置已经在图中标注出来了,条件是target_x == target_y。target_x、target_y为设定的目标点。

                                                              

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值