• 题目描述

    标题:螺旋折线

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

如图所示的螺旋折线经过平面上所有整点恰好一次。  
对于整点(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为设定的目标点。

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

相关文章:

  • 2021-06-28
  • 2021-07-25
  • 2021-04-21
  • 2021-06-13
  • 2021-08-04
  • 2021-10-16
猜你喜欢
  • 2021-06-25
  • 2022-01-07
  • 2021-10-26
  • 2021-09-22
  • 2021-08-28
  • 2022-01-19
相关资源
相似解决方案