items links:点击打开链接
A bishop is a piece used in thegame of chess which is played on a board of square grids. A bishop can only movediagonally from its current position and two bishops attack each other if oneis on the path of the other. In the following figure, the dark squaresrepresent the reachable locations for bishop B1 formits current position. The figure also shows that the bishopsB1and B2 are in attacking positions whereasB1and B3 are not.B2 and B3are also in non-attacking positions.

Now, given two numbers nand k, your job is to determine the number of ways one can putkbishops on an n × nchessboard so that no two of them are in attacking positions.
analysis: the moment I read the problem, an idea of dfs occurred to me. so I tryed it .It turned out to be a result of TL!!!
For the n is no more than 8,I decided to use array to store all the possible answers.
the former code
later, I got the point why I got time out
e.g.
in put
8 15
output
0
the example will cost you a few seconds (surely more the 2).T ^T
there are some good example
input:
-
8 6
4 4
8 15
8 12
8 0
5 1
5 5
5 9
8 10
1 1
1 0
7 8
0 0
-
5599888
260
0
489536
0
25
3368
0
12448832
1
0
867328
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
long k, n, ans,vis[3][60],map[20][20];
void solve ( long dep, long x, long y )
{
if ( dep == k )
{
ans ++;//printf("aaa\n");
return;
}
for(long i=x; i<=n; i++)
{
int tmp=1;
if(i==x) tmp=y+1;
for(long j=tmp; j<=n; j++)
{
if(!map[i][j]&&!vis[0][i-j+n]&&!vis[1][i+j])
{
map[i][j]=vis[0][i-j+n]=vis[1][i+j]=1;
solve(dep+1,i,j);
map[i][j]=vis[0][i-j+n]=vis[1][i+j]=0;
}
}
}
}
int main()
{
long i,j;
while (1 )
{
scanf ( "%ld %ld", &n, &k );
if (!n&&!k) break;
ans = 0;
memset ( map, 0, sizeof(map));
memset ( vis, 0, sizeof(vis) );
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
{
map[i][j]=vis[0][i-j+n]=vis[1][i+j]=1;
solve ( 1, i, j );
map[i][j]=vis[0][i-j+n]=vis[1][i+j]=0;
}
printf ( "%ld\n", ans );
}
return 0;
}
the latter code
#include<iostream>
using namespace std;
const long cheat[9][67]={{0},
{1,1},
{1,4,4},
{1,9,26,26,8},
{1,16,92,232,260,112,16},
{1,25,240,1124,2728,3368,1960,440,32},
{1,36,520,3896,16428,39680,53744,38368,12944,1600,64},
{1,49,994,10894,70792,282248,692320,1022320,867328,389312,81184,5792,128},
{1,64,1736,26192,242856,1444928,5599888,14082528,22522960,22057472,12448832,3672448,489536,20224,256}};
int main()
{
long n,k;
while(cin>>n>>k)
{
if(n==0&&k==0) break;
cout<<cheat[n][k]<<endl;
}
return 0;
}
other excellent solutions
1.棋盘多项式:http://blog.tianya.cn/blogger/post_show.asp?idWriter=0&Key=0&BlogID=397009&PostID=6849511
2.dp:http://www.cppblog.com/lzh/archive/2010/08/25/124684.html

本文探讨了在n×n的国际象棋棋盘上放置k个象,使得任意两个象都不处于相互攻击的位置的问题。提供了两种解决方案,一种是通过递归搜索的方法,另一种则是利用预计算表格的方式大幅提高效率。
1248

被折叠的 条评论
为什么被折叠?



