跳到正文

题解

题解:P8189 [USACO22FEB] Redistributing Gifts G

Purslane约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
题目
P8189

版本

  1. v1当前

Solution

省选前一晚上没啥事干,随便写写题解吧。

显然最终的结构是若干置换环。

所以我们可以这样设计状压 DP:设 dpS,s,tdp_{S,s,t} 为,使用 SS 种的点,能拼成多少种合法的、s→ts \to t 的链。判断 (t,s)(t,s) 能否连边贡献到 fSf_S 表示将 SS 变成一个环的方案数,然后使用子集卷积(集合幂级数的 exp⁡\exp)得到 gSg_S 表示使用 SS 种的点的答案,复杂度 O(n22n)O(n^2 2^n)。

但是这样做挺魔怔的。首先,我们可以不记录 ss——钦定 ss 为 SS 中的最小值即可;其次,如果已经拼成了若干个环,我们不需要记录其他的环是怎么处理的。也就是说,我们只需要记录 dpS,tdp_{S,t} 表示,将 SS 中的点搞成若干个环,以及一条 min⁡(S)→t\min(S) \to t 的链的方案数。

那么很容易做到 O(n22n)O(n^2 2^n),但是变得特别好写。

C++
#include<bits/stdc++.h>
#define int long long
#define ffor(i,a,b) for(int i=(a);i<=(b);i++)
#define roff(i,a,b) for(int i=(a);i>=(b);i--)
using namespace std;
const int MAXN=20,MAXM=(1<<18)+10;
int n,q,ok[MAXN][MAXN],res[MAXM],dp[MAXM][MAXN],lb[MAXM];
signed main() {
	ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	cin>>n;
	ffor(i,1,n) {
		int tmp=1;
		ffor(j,1,n) {int id;cin>>id,ok[i][id]=tmp,tmp&=(id!=i);}
	}
	res[0]=1;
	ffor(i,1,n) dp[(1<<i-1)][i]=1,lb[(1<<i-1)]=i;
	ffor(i,1,(1<<n)-1) {
		int s=lb[i&-i];
		ffor(t,s,n) if(ok[s][t]) res[i]+=dp[i][t];
		ffor(t,1,s-1) dp[i+(1<<t-1)][t]+=res[i];
		ffor(l,s,n) ffor(t,s+1,n) if(!(i&(1<<t-1))&&ok[t][l]) dp[i+(1<<t-1)][t]+=dp[i][l];
	}
	cin>>q;
	ffor(i,1,q) {
		string S;
		cin>>S;
		int o=0,oo=0;
		ffor(j,1,n) if(S[j-1]=='G') o+=(1<<j-1); else oo+=(1<<j-1);
		cout<<res[o]*res[oo]<<'\n';
	}
	return 0;
}
原文