热身赛10--K - Knightmare(bfs打表找规律)

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Submit Status

Description

A knight jumps around an infinite chessboard. The chessboard is an unexplored territory. In the spirit of explorers, whoever stands on a square for the first time claims the ownership of this square. The knight initially owns the square he stands, and jumps $N$ times before he gets bored.
Recall that a knight can jump in 8 directions. Each direction consists of two squares forward and then one squaure sidways.


After $N$ jumps, how many squares can possibly be claimed as territory of the knight? As $N$ can be really large, this becomes a nightmare to the knight who is not very good at math. Can you help to answer this question?

Input

The first line of the input gives the number of test cases, $T$. $T$ test cases follow.
Each test case contains only one number $N$, indicating how many times the knight jumps.
$1 \leq T \leq 10^5$
$0 \leq N \leq 10^9$

Output

For each test case, output one line containing “Case #x: y”, where $x$ is the test case number (starting from 1) and $y$ is the number of squares that can possibly be claimed by the knight.

Sample Input

3

0

1

7

Sample Output

Case #1: 1

Case #2: 9

Case #3: 649

【分析】先用bfs打表,代码:

#include<bits/stdc++.h>
using namespace std;
int n,m;
int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
int vis[1000][1000];
int ans[100];
struct node{
	int x,y;
	int step;
};
int main()
{
	memset(vis,0,sizeof(vis));//都没访问过
	queue<node> q;
	node p;
	p.x=500,p.y=500,p.step=0;
	ans[0]=1;
	vis[500][500]=1;
	q.push(p);
	while(!q.empty())
	{
		p=q.front();
		q.pop();
		if(p.step==20)continue;
		for(int k=0;k<8;k++)
		{
			int xx=p.x+dir[k][0];
			int yy=p.y+dir[k][1];
			if(vis[xx][yy])continue;//如果该点已经访问过,不再执行
			vis[xx][yy]=1;
			node tmp;
			tmp.x=xx;tmp.y=yy;tmp.step=p.step+1;
			ans[tmp.step]++;
			q.push(tmp); 
		}
	} 
	int sum=1;
	for(int i=1;i<20;i++)
	{
		sum+=ans[i];
		cout<<"sum="<<sum<<"		layer"<<i<<":"<<ans[i];
		cout<<"\t 	差:"<<ans[i]-ans[i-1]<<endl;
	}
	return 0;
	
}

第一列表示全部领域个数,第二列是每一层的个数,第三列是每一层递增数。

由上结果,可知,从第六层开始,每一层都是增加了28。注意范围unsigned long long;

#include<bits/stdc++.h>
using namespace std;  
int ans[8]={1,9,41,109,205,325,473,649};  
int main()  
{  
    int t;  
    scanf("%d",&t);  
    unsigned long long num;  
    for(int kase=1; kase<=t;kase++){  
        scanf("%llu",&num);  
        if(num<=6)  
            printf("Case #%d: %d\n",kase,ans[num]);  
        else{  
            unsigned long long t = num-6;  
            unsigned long long anss=473;  
            anss+=148*t;  
            unsigned long long tt = ((1+t)*t)/2;  
            anss+=28*tt;  
            printf("Case #%d: %llu\n",kase,anss);  
        }  
    }  
    return 0;  
}  

猜你喜欢

转载自blog.csdn.net/qq_38735931/article/details/82025106