2011年8月4日 星期四

[ACM 10161] Ant on a Chessboard

 內容 :
有一天,有一隻叫做小強的螞蟻來到一個M*M的棋盤上。他想要把棋盤的每一格都走過。他走的路徑有點奇怪,像一條蛇一樣,他走的速度是每秒一格(請參考下圖中紅色的路徑,代表1-25秒的位置)。
從上圖可知:在第1秒時他的位置在(1,1),在第8秒時他的位置在(2,3),在第20秒時他的位置在(5,4)。你的任務就是要求出在某一秒時小強在棋盤上的位置。(你可以假設棋盤有夠大)

 輸入說明 :
每行一個整數N(1 <= N <= 2000000000),代表給的時間。N=0代表輸入結束。
輸出說明 :
根據輸入的時間N,輸出其時小強在棋盤上的位置(x,y),請參考Sample Output。
範例輸入 :
8
20
25 
0

範例輸出 :
2 3
5 4
1 5




這份是朋友教的,所以程式風格比其他自己寫的好太多了 XD


/**********************************************************************************/
/*  Problem: c048 "Ant on a Chessboard" from ACM 10161                            */
/*  Language: C                                                                   */
/*  Result: AC (8ms, 356KB) on ZeroJudge                                          */
/*  Author: diiuuli520 at 2008-08-20 01:01:09                                     */
/**********************************************************************************/
#include <stdio.h>
#include <math.h>
#define SIZE_a 100000
int main(void)
{
  int N;
  int up=1,bottom=1;
  int now_left,now_right,prev_left,prev_right;
  int flag,limit;
  int i,n;
  while(scanf("%d",&N)==1)
  {
    if(!N)  break;
    n=(int)(floor(sqrt(N))+0.5);
    if((n%2)==0)
    {
      prev_left=n;
      prev_right=1;
      up=n;
      bottom=1;
      flag=6;
      now_left=prev_left;
      now_right=prev_right;
    }
    else
    {
      prev_left=1;
      prev_right=n;
      up=n;
      bottom=1;
      flag=3;
      now_left=prev_left;
      now_right=prev_right;
    }
    limit=N-n*n;
    for(i=0; i<limit; ++i)
    {
      now_left=prev_left;
      now_right=prev_right;
      if(flag==1)
      {
        if(now_left==up)
        {
          now_right+=1;
          if(now_right==up)
            flag=2;
        }
      }
      else if(flag==2)
      {
        if(now_right==up)
        {
          now_left-=1;
          if(now_left==bottom)
            flag=3;
        }
      }
      else if(flag==3)
      {
        if(now_left==bottom)
        {
          now_right+=1;
          up+=1;
          if(now_right==up)
            flag=4;
        }
      }
      else if(flag==4)
      {
        if(now_right==up)
        {
          now_left+=1;
          if(now_left==up)
            flag=5;
        }
      }
      else if(flag==5)
      {
        if(now_left==up)
        {
          now_right-=1;
          if(now_right==bottom)
            flag=6;
        }
      }
      else if(flag==6)
      {
        if(now_right==bottom)
        {
          now_left+=1;
          up+=1;
          if(now_left==up)
            flag=1;
        }
      }
      prev_left=now_left;
      prev_right=now_right;
    }
    printf("%d %d\n",now_left,now_right);
  }
  return 0;
}

沒有留言:

張貼留言