您的位置:首页 > 其它

ants(插头DP)

2016-02-24 17:18 232 查看
有一个N*N的矩阵,需要用若干循环将其铺满,使得每个格子都处于一个循环上,求方案数,逆时针和顺时针的循环算作不同的方案。n<=10.

插头DP,用0表示空,1表示插向轮廓线下侧的插头,2表示插向轮廓线上侧的插头。一共有9种转移,分类讨论即可。实现的过程中可以用4进制来代替3进制。

由于我直接用的city那道题的插头DP模板,结果N=8以上就卡了很久。注意换行的时候不能直接移位,因为会产生不合法的状态,要把移出去的头砍掉,或者在转移的时候特判。还有转移的时候最好在各种地方加上防止不合法状态的特判,这样才能保证转移时候的状态数在预计的范围内。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<set>
#include<assert.h>
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define erp(i,a,b) for(int i=a;i>=b;--i)
#define getbit(x,y) (((x) >> ((y)<<1)) & 3)
#define bit(x,y) ((x)<<((y)<<1))
#define clrbit(x,i,j) ((x) & (~(3<<((i)<<1))) & (~(3<<((j)<<1))))
#define LL long long
using namespace std;
const int mo = 100003, MAXS = 100000;
int N;

struct Node
{
int s, nxt;
LL val;
};
struct Hash
{
Node e[MAXS];
int adj[mo], ec;
void init()
{
memset(adj, -1, sizeof adj);
ec = 0;
}
void push(int s, LL v)
{
int ha = s%mo;
for (int i = adj[ha]; ~i; i=e[i].nxt)
if (e[i].s == s)
{
e[i].val += v;
return;
}
e[ec].val = v, e[ec].s = s;
e[ec].nxt = adj[ha];
adj[ha] = ec++;
}
} dp[2];

void work(int i, int j, int cur)
{
dp[cur].init();
rep(k, 0, dp[cur^1].ec-1)
{
int lass = dp[cur^1].e[k].s;
if (lass >= (1<<((N+1)<<1))) continue; //这个非常重要!!
int L = getbit(lass, j-1);
int U = getbit(lass, j);
int s = clrbit(lass, j-1, j);
LL las = dp[cur^1].e[k].val;
if (!L && !U)
{
if (j!=N) dp[cur].push(s | bit(1,j) | bit(2,j-1), las);
if (i!=N) dp[cur].push(s | bit(2,j) | bit(1,j-1), las);
}
else if (!L && U==1)
{
dp[cur].push(s | bit(0,j-1) | bit(1,j), las);
if (i!=N) dp[cur].push(s | bit(1,j-1) | bit(0,j), las);
}
else if (!L && U==2)
{
dp[cur].push(s | bit(0,j-1) | bit(2,j), las);
dp[cur].push(s | bit(2,j-1) | bit(0,j), las);
}
else if (L==1 && !U)
{
dp[cur].push(s | bit(0,j-1) | bit(1,j), las);
if (i!=N) dp[cur].push(s | bit(1,j-1) | bit(0,j), las);
}
else if (L==1 && U==2)
{
dp[cur].push(s, las);
}
else if (L==2 && !U)
{
dp[cur].push(s | bit(0,j-1) | bit(2,j), las);
dp[cur].push(s | bit(2,j-1) | bit(0,j), las);
}
else if (L==2 && U==1)
{
dp[cur].push(s, las);
}
}
}

LL solve()
{
dp[0].init(), dp[0].push(0, 1);
int cur = 0;
rep(i, 1, N)
{
rep(k, 0, dp[cur].ec-1)
dp[cur].e[k].s <<= 2; //注意这样写会产生大量不合法状态。转移时特判即可。
rep(j, 1, N)
{
cur ^= 1;
work(i, j, cur);
}
}
rep(k, 0, dp[cur].ec-1)
if (dp[cur].e[k].s == 0)
return dp[cur].e[k].val;
return 0;
}

int main()
{
cin >> N;
if (N&1) puts("0");
else cout << solve() << '\n';
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: