【LOJ #6433】「PKUSC2018」最大前缀和(状压DP)
也挺傻逼的
很小
考虑如果暴力计算每种前缀的集合为最大前缀和的答案
需要满足剩下的组成的任意前缀和都小于0
表示集合排列出来任意前缀和都小于0的方案数
类似考虑一个集合作为最大前缀和
把这个序列反过来
则一定不存在前缀和小于0
也可以类似的定义一个来做
注意最大前缀和不能不选,所以如果集合的和小于0也是合法的,只是不能继续转移
注意一段和为处理一下算在还是内
#include<bits/stdc++.h>
using namespace std;
#define cs const
#define re register
#define pii pair<int,int>
#define fi first
#define se second
#define ll long long
#define pb push_back
cs int RLEN=1<<20|1;
inline char gc(){
static char ibuf[RLEN],*ib,*ob;
(ib==ob)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ib==ob)?EOF:*ib++;
}
inline int read(){
char ch=gc();
int res=0;bool f=1;
while(!isdigit(ch))f^=ch=='-',ch=gc();
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
return f?res:-res;
}
template<class tp>inline void chemx(tp &a,tp b){a<b?a=b:0;}
template<class tp>inline void chemn(tp &a,tp b){a>b?a=b:0;}
cs int mod=998244353;
inline int add(int a,int b){return (a+=b)>=mod?(a-mod):a;}
inline void Add(int &a,int b){(a+=b)>=mod?(a-=mod):0;}
inline int dec(int a,int b){a-=b;return a+(a>>31&mod);}
inline void Dec(int &a,int b){a-=b,a+=a>>31&mod;}
inline int mul(int a,int b){static ll r;r=1ll*a*b;return (r>=mod)?(r%mod):r;}
inline void Mul(int &a,int b){static ll r;r=1ll*a*b,a=(r>=mod)?(r%mod):r;}
inline int ksm(int a,int b,int res=1){for(;b;b>>=1,Mul(a,a))(b&1)&&(Mul(res,a),1);return res;}
inline int Inv(int x){return ksm(x,mod-2);}
inline int fix(int x){x%=mod;return (x<0)?(x+mod):x;}
cs int N=21,M=(1<<21)|1;
int n,a[N],f[M],dp[M],g[M],lim,s[M],pp[M];
inline int lb(int x){return x&(-x);}
int main(){
#ifdef Stargazer
freopen("lx.in","r",stdin);
#endif
n=read(),lim=1<<n;
for(int i=1;i<=n;i++)a[i]=read(),pp[1<<(i-1)]=i;
for(int i=1;i<lim;i++)s[i]=s[i^lb(i)]+a[pp[lb(i)]];
for(int i=1;i<=n;i++)if(a[i]<=0)g[1<<(i-1)]=1;
g[0]=1;
for(int i=1;i<lim;i++){
if(s[i]>0){g[i]=0;continue;}
for(int j=1;j<=n;j++)if(!((1<<(j-1))&i)){
Add(g[i+(1<<(j-1))],g[i]);
}
}
for(int i=1;i<=n;i++)f[1<<(i-1)]=1;
for(int i=1;i<lim;i++){
if(s[i]<=0){continue;}
for(int j=1;j<=n;j++)if(!((1<<(j-1))&i)){
Add(f[i+(1<<(j-1))],f[i]);
}
}
int ret=0;
for(int i=0;i<lim;i++){
// cout<<i<<" "<<s[i]<<" "<<f[i]<<" "<<g[(lim-1)^i]<<" "<<((lim-1)^i)<<'\n';
Add(ret,mul(fix(s[i]),mul(f[i],g[(lim-1)^i])));
}
cout<<ret<<'\n';
return 0;
}