Luogu P1896 [SCOI2005] Mutual Non-aggression DP

Topic description

How many ways are there to place K kings on an N×N chessboard so that they do not attack each other. The king can attack it up, down, left and right, as well as one grid in each of the eight directions of the upper left, lower right, upper right and lower right, a total of 8 grids.

Input and output format

Input format:

There is only one line, containing two numbers N, K ( 1 <=N <=9, 0 <= K <= N * N)

Output format:

The number of solutions obtained

Input and output example

Input example #1: 
3 2
Sample output #1: 
16



answer

State pressure dp entry questions. The basic concept of the shape pressure dp is not repeated here.

#include<cstdio>
using namespace std;
int n,k,num[512];
long long f[10][82][512];//Ten years OI can't open longlong see ancestors
bool flag[512]={ 0};
long long ans=0;
void init()//Preprocessing
{
for(int i=0;i<(1<<n);i++) Is it legal to enumerate a line of possible states
{
if(!( i&(i<<1)))
{
flag[i]=true;
int t=i;
while(t) if the state is legal then count the number of kings in the state
{
num[i]+=(t&1);
t>>=1;
}
f[1][num[i]][i]=1;
}
}
}
int main()
{
scanf("%d%d",&n,&k);
init();
for (int i=2;i<=n;i++)//The first line has been calculated, so start from the second line
for(int j=0;j<=k;j++)//k is the first i line Total number of kings
for(int now=0;now<(1<<n);now++)//enumerate the state of the i-th line
{
if(!flag[now]||num[now]>j)continue;//If the state is illegal, skip
for(int pre=0;pre<(1<<n);pre++)//violent enumeration The state of a line if the state of the previous line is the same as

                                                                                       Skip the current line status conflict
{
if(!flag[pre]||(now&pre)||((now<<1)&pre)||((now>>1)&pre))continue;
f[i][ j][now]+=f[i-1][j-num[now]][pre];//State transition equation
}
}
for(int i=0;i<(1<<n);i++) ans+=f[n][k][i];//Add up the number of state schemes in the last line of enumeration. Note that longlong
printf("%lld",ans);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325362181&siteId=291194637