Codeforces525E Anya and Cubes(双向搜索)
题目
Source
http://codeforces.com/contest/525/problem/E
Description
Anya loves to fold and stick. Today she decided to do just that.
Anya has n cubes lying in a line and numbered from 1 to n from left to right, with natural numbers written on them. She also has k stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes.
Anya can stick an exclamation mark on the cube and get the factorial of the number written on the cube. For example, if a cube reads 5, then after the sticking it reads 5!, which equals 120.
You need to help Anya count how many ways there are to choose some of the cubes and stick on some of the chosen cubes at most k exclamation marks so that the sum of the numbers written on the chosen cubes after the sticking becomes equal to S. Anya can stick at most one exclamation mark on each cube. Can you do it?
Two ways are considered the same if they have the same set of chosen cubes and the same set of cubes with exclamation marks.
Input
The first line of the input contains three space-separated integers n, k and S (1 ≤ n ≤ 25, 0 ≤ k ≤ n, 1 ≤ S ≤ 1016) — the number of cubes and the number of stickers that Anya has, and the sum that she needs to get.
The second line contains n positive integers ai (1 ≤ ai ≤ 109) — the numbers, written on the cubes. The cubes in the input are described in the order from left to right, starting from the first one.
Multiple cubes can contain the same numbers.
Output
Output the number of ways to choose some number of cubes and stick exclamation marks on some of them so that the sum of the numbers became equal to the given number S.
Sample Input
2 2 30
4 3
2 2 7
4 3
3 1 1
1 1 1
Sample Output
1
1
6
分析
题目大概说有n个数,从中选出若干个数,可以再从选择的数中选择不超过k个数让它们变为自身的阶乘,问有几种方案使得选出来的若干个数的和等于S。
将n个数分成两边,左边dfs不选、选、选且变为阶乘搜出所有方案,用map统计各个和的情况;右边一样,利用map更新答案。
不过,由于最后还要枚举更新答案,超时了;把左边搜索的数量增加一点,变为min(n/2+2,n)就过了。
看了下官方题解,题解说先用count()判断map有没有再用这样会快,果然快了1倍。
代码
#include<cstdio> #include<cstring> #include<map> #include<algorithm> using namespace std; long long S; int n,m,a[26]; long long fact[20]={1}; long long ans; map<long long,int> cnt[26]; int tmp; void dfs1(int x,int y,long long s){ if(s>S || y>m) return; if(x==tmp){ ++cnt[y][s]; return; } dfs1(x+1,y,s); dfs1(x+1,y,s+a[x]); if(a[x]<19) dfs1(x+1,y+1,s+fact[a[x]]); } void dfs2(int x,int y,long long s){ if(s>S || y>m) return; if(x==n){ for(int i=0; i+y<=m; ++i){ if(cnt[i].count(S-s)) ans+=cnt[i][S-s]; } return; } dfs2(x+1,y,s); dfs2(x+1,y,s+a[x]); if(a[x]<19) dfs2(x+1,y+1,s+fact[a[x]]); } int main(){ for(int i=1; i<20; ++i){ fact[i]=fact[i-1]*i; } scanf("%d%d%lld",&n,&m,&S); for(int i=0; i<n; ++i){ scanf("%d",a+i); } tmp=min(n,n/2+2); dfs1(0,0,0); dfs2(tmp,0,0); printf("%lld\n",ans); return 0; }