U636725 插入阶乘
chillchill · · 个人记录
传送门 U636725 插入阶乘
数据
只有1组数据
1.in
10 3 1000
1 2 6 10 100 200 300 400 500 600
1.out
5
神圣的代码
累死了。勉强勉强吧,我的码风在班里算好的。 ——China_TSJ77
纯净无注释版,适用于ctj
#include <iostream>
#include <unordered_map>
#define ll long long
using namespace std;
ll n,k,s,res,a[30],fac[30];
unordered_map <ll,ll> mp[30];
void dfs1(int step,int cnt,ll tot)
{
if (step>n/2)
{
mp[cnt][tot]++;
return ;
}
dfs1(step+1,cnt,tot);
if (tot+a[step]<=s)
{
dfs1(step+1,cnt,tot+a[step]);
}
if (a[step]<=19 && tot+fac[a[step]]<=s && cnt<k)
{
dfs1(step+1,cnt+1,tot+fac[a[step]]);
}
}
void dfs2(int step,int cnt,ll tot)
{
if (step>=n+1)
{
for (int i=0;i+cnt<=k;i++)
{
if (mp[i].count(s-tot))
{
res+=mp[i][s-tot];
}
}
return ;
}
dfs2(step+1,cnt,tot);
if (tot+a[step]<=s)
{
dfs2(step+1,cnt,tot+a[step]);
}
if (a[step]<=19 && tot+fac[a[step]]<=s && cnt<k)
{
dfs2(step+1,cnt+1,tot+fac[a[step]]);
}
}
int main()
{
cin >> n >> k >> s;
for (int i=1;i<=n;i++)
{
cin >> a[i];
}
fac[0]=1;
for (int i=1;i<=19;i++) fac[i]=fac[i-1]*i;
dfs1(1,0,0);
dfs2(n/2+1,0,0);
cout << res << '\n';
return 0;
}
注释版
#include <iostream>
#include <unordered_map>
#define ll long long
using namespace std;
ll n,k,s,res,a[30],fac[30];
unordered_map <ll,ll> mp[30];
// mp[i][j] i次阶乘,得到j的方案数量
void dfs1(int step,int cnt,ll tot)
// cnt 已用的阶乘次数 tot 和
{
if (step>n/2) // 处理完
//用cnt次阶乘得到tot的方案+1
{
mp[cnt][tot]++;
return ;
}
// 不选
dfs1(step+1,cnt,tot);
// 不用阶乘
if (tot+a[step]<=s)
{
dfs1(step+1,cnt,tot+a[step]);
}
// 用阶乘 a[step]<=19 要是太大了会炸
if (a[step]<=19 && tot+fac[a[step]]<=s && cnt<k)
{
dfs1(step+1,cnt+1,tot+fac[a[step]]);
}
}
void dfs2(int step,int cnt,ll tot)
{
if (step>=n+1) // 补全方案
{
for (int i=0;i+cnt<=k;i++)
// i左半阶乘次数
{
if (mp[i].count(s-tot))
{
res+=mp[i][s-tot];
}
}
return ;
}
// 同
dfs2(step+1,cnt,tot);
if (tot+a[step]<=s)
{
dfs2(step+1,cnt,tot+a[step]);
}
if (a[step]<=19 && tot+fac[a[step]]<=s && cnt<k)
{
dfs2(step+1,cnt+1,tot+fac[a[step]]);
}
}
int main()
{
cin >> n >> k >> s;
for (int i=1;i<=n;i++)
{
cin >> a[i];
}
fac[0]=1;
for (int i=1;i<=19;i++) fac[i]=fac[i-1]*i;
dfs1(1,0,0);
dfs2(n/2+1,0,0);
cout << res << '\n';
return 0;
}