一个ACM题的求解过程

题目:

 Problem A.Ant on a Chessboard(10161) 

Background

  One day, an ant called Alice came to an M*M chessboard. She wanted to go around all the grids. So she began to walk along the chessboard according to this way: (you can assume that her speed is one grid per second)

  At the first second, Alice was standing at (1,1). Firstly she went up for a grid, then a grid to the right, a grid downward. After that, she went a grid to the right, then two grids upward, and then two grids to the left…in a word, the path was like a snake.

  For example, her first 25 seconds went like this:

  ( the numbers in the grids stands for the time when she went into the grids)

 

At the 8th second , she was at (2,3), and at 20th second, she was at (5,4).

Your task is to decide where she was at a given time.

(you can assume that M is large enough)

Input

  Input file will contain several lines, and each line contains a number N(1<=N<=2*10^9), which stands for the time. The file will be ended with a line that contains a number 0.

Output

  For each input situation you should print a line with two numbers (x, y), the column and the row number, there must be only a space between them.

Sample Input

8

20

25

0

Sample Output

2 3

5 4

1 5

 

一看到这题目 ,我们都知道第一思路是找出它的绕行规律

经过观察我们可以发现,绕行的方向有一个周期,就是六次转向为一个循环。这六次转向中,第一次都是向上走一步的,第二次向右走,第三次向下,第四次向右走一步,第五次向上,第六次向左。假设走到第n个循环内,第二次转向时走了2*n-1步,第三次也是走了这么多,第五次向上走了2*n步,第六次也走了这么多。最后在化成坐标时,还要给它加一,因为走一步要涉及两格。这就是一般规律。有了这规律之后,接下来就是用程序来表达这个思路了。

下面我就直接给出我写的程序。

#include<iostream>
using namespace std;

//定义两个全局变量来存放位置坐标
int posX,posY;

//先统计出是第几个六(即六次换向)
void countSix(int n,int &count,int &diff)
{
 int sum = 8; //第一个六是8步,第二个六是16步,第三个六是24步……
 int t = 2; //用来辅助算出总步数
 count = 1; //第几个六
 n --;
 while(sum < n)
 {
  sum += 8*t;
  t ++;
  count ++;
 }
 if(sum != n)
  diff = n - sum + 8*(t-1); //表示输入数与第count-1个六的总数之差
 else
  diff = 0;
}

int main()
{
 int n,count,diff;
 char flag = 'y';
 while(flag == 'y')
 {
  printf("Please input the number of the step:");
  scanf("%d",&n);
  countSix(n,count,diff);
  //计算坐标
  if(diff == 1 )
  {
   posX = 1;
   posY = 2*count;
  }
  else if(diff == 0)
  {
   posX = 1;
   posY = 2*count + 1;
  }
  else if(diff<=2*count)
  {
   posX = diff ;
   posY = 2*count;
  }
  else if(diff<4*count)
  {
   posX = 2*count;
   posY = 4*count-diff;
  }
  else if(diff == 4*count)
  {
   posX = 2*count + 1;
   posY = 1;
  }
  else if(diff<=6*count)
  {
   posX = 2*count + 1;
   posY = diff - 4*count + 1;
  }
  else
  {
   posX = 8*count - diff + 1;
   posY = 2*count + 1;
  }

  printf("%d,%d/n",posX,posY);
  printf("/nContinue?(y/n):");
  getchar();
  scanf("%c",&flag);
 }
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值