欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

[CQOI2012] 局部极小值(状压DP + 容斥 + 搜索)

发布时间:2023/12/3 编程问答 52 豆豆
生活随笔 收集整理的这篇文章主要介绍了 [CQOI2012] 局部极小值(状压DP + 容斥 + 搜索) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

problem

luogu-P3160

solution

这么小的数据范围,非暴力不状压。暴力 O(28!)O(28!)O(28!) 呵呵呵可以拉走了。

我们不妨从小到大填数字,这样如果局部极小值点还没有填的话,周围的九宫格就一定不能被填。

dp(s,i):dp(s,i):dp(s,i): 局部极小值点的是否填了数字的情况 sss,已经填完了 [1,i][1,i][1,i] 以内的数字。

  • i+1i+1i+1 填入非极小值点影响区域。

    dp(s,i+1)←dp(s,i)∗(cnt−i)dp(s,i+1)\leftarrow dp(s,i)*(cnt-i)dp(s,i+1)dp(s,i)(cnti)

    cnt:cnt:cnt: 除去现在还没有被填的极小值以及其九宫格内的格子,剩下的个子数量,显然要空出 n−cntn-cntncnt 个格子去满足极小值点周围的要求。

    不能简单的用 9×9\times9× 极小值点个数,显然两个极小值的九宫格有可能重叠部分。

  • i+1i+1i+1 填入极小值点。

    那么该极小值一旦被填,就可以释放周围九宫格的限制。

    dp(s∣(1<<j),i+1)←dp(s,i)dp(s|(1<<j),i+1)\leftarrow dp(s,i)dp(s(1<<j),i+1)dp(s,i)

具体可见下方代码。

但是这样 dpdpdp 我们发现一个致命的问题。

我们会计算到『某些九宫格内中心点不是 X\text{X}X,但中心点又恰好满足局部极小值的要求』的情况。

而包含这种情况的方案在题目中是不合法的。题目已经给出了所有局部极小值点,其余点就必须不是。

这里我们就想到了 容斥 。不好意思我没有想到

我们可以额外多钦定了 kkk 个极小值点,那么算出来的 dpdpdp 应该前面配一个 (−1)k(-1)^k(1)k 容斥出最后的答案。

而可以同时存在的局部极小值点个数并没有多少,顶多 888 个。

所以 kkk 并不会多大。

我们完全可以搜索做。

code

#include <bits/stdc++.h> using namespace std; #define int long long #define mod 12345678 int n, m, ans; int px[10], py[10]; char ch[10][10]; int vis[10][10]; int f[1 << 10][30];bool inside( int x, int y ) {if( x < 0 or x >= n or y < 0 or y >= m ) return 0;else return 1; }int calc() {memset( f, 0, sizeof( f ) );int tot = 0;for( int i = 0;i < n;i ++ )for( int j = 0;j < m;j ++ )if( ch[i][j] == 'X')px[tot] = i, py[tot] = j, ++ tot;f[0][0] = 1;for( int s = 0;s < (1 << tot);s ++ ) {memset( vis, 0, sizeof( vis ) );for( int i = 0;i < tot;i ++ )if( ! (s >> i & 1) )for( int x = -1;x <= 1;x ++ )for( int y = -1;y <= 1;y ++ )if( inside( px[i] + x, py[i] + y) )vis[px[i] + x][py[i] + y] = 1;int cnt = n * m;for( int i = 0;i < n;i ++ )for( int j = 0;j < m;j ++ )cnt -= vis[i][j];for( int i = 0;i <= cnt;i ++ )if( f[s][i] ) {( f[s][i + 1] += f[s][i] * ( cnt - i ) ) %= mod;for( int j = 0;j < tot;j ++ )if( ! (s >> j & 1) )( f[s | (1 << j)][i + 1] += f[s][i] ) %= mod;}}return f[(1 << tot) - 1][n * m]; }void dfs( int x, int y, int k ) {if( x >= n ) return ( ans += k * calc() ) %= mod, void();if( y >= m ) dfs( x + 1, 0, k );else {dfs( x, y + 1, k );bool flag = 1;for( int i = -1;i <= 1;i ++ )for( int j = -1;j <= 1;j ++ )if( inside( x + i, y + j ) and ch[x + i][y + j] == 'X' )flag = 0;if( flag ) {ch[x][y] = 'X';dfs( x, y + 1, -k );ch[x][y] = '.';}} }signed main() {scanf( "%lld %lld", &n, &m );for( int i = 0;i < n;i ++ )scanf( "%s", ch[i] );for( int i = 0;i < n;i ++ )for( int j = 0;j < m;j ++ )if( ch[i][j] == 'X' ) for( int x = -1;x <= 1;x ++ )for( int y = -1;y <= 1;y ++ )if( ( x or y ) and inside( i + x, j + y ) and ch[i + x][j + y] == 'X' )return puts("0"), 0;dfs( 0, 0, 1 );printf( "%lld\n", ( ans + mod ) % mod );return 0; }

总结

以上是生活随笔为你收集整理的[CQOI2012] 局部极小值(状压DP + 容斥 + 搜索)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。