状态压缩Dp,按行处理。
复杂度: O(n∗k∗3n)
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
const int maxn = 15, maxk = 105, sz = 10;
struct Trans
{
int fr,to,imp;
Trans(int fr = 0,int to = 0,int imp = 0):fr(fr),to(to),imp(imp){}
};
int n, k;
Trans ts[1<<(sz<<1)]; int tl;
long long f[maxn][maxk][1<<sz], ans;
void DFS(int col,int last,int now,int cnt)
{
if(col == n)
ts[++tl] = Trans(last,now,cnt);
else
{
DFS(col + 1, last, now, cnt);
if(!col || (!(last&(1<<(col-1))) && !(now&(1<<(col-1)))))
{
DFS(col + 1, last|(1<<col), now, cnt);
DFS(col + 1, last, now|(1<<col), cnt + 1);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("sgu223.in","r",stdin);
freopen("sgu223.out","w",stdout);
#endif
std::cin >> n >> k;
f[0][0][0] = 1;
DFS(0,0,0,0);
for(int i = 1; i <= n; i++)
for(int j = 0; j <= k; j++)
for(int p = 1; p <= tl; p++)
if(j - ts[p].imp >= 0)
f[i][j][ts[p].to] += f[i-1][j-ts[p].imp][ts[p].fr];
for(int i = 0; i < (1<<n); i++)
ans += f[n][k][i];
std::cout << ans;
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
本文深入解析状态压缩动态规划,一种高效解决组合优化问题的技术。通过示例代码详细讲解了如何利用位运算和递归实现复杂度优化,适用于解决大规模状态转移问题。特别关注行处理技巧,降低内存消耗。
786

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



