传送门:http://hihocoder.com/contest/hihointerview22/problem/3
题意:给一个序列在序列中添加+或者-,使得运算结果为s,求方法数
思路:
强搜肯定不行,这题可以转换成01背包求解
先求出序列的sum,多出的sum-s肯定有一半是要加上去的,还有一半是要减去的
所以背包容量为(sum-s)/2,背包价值为方案数
代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
#define mod 1000000007
typedef long long ll;
const int N = 100005;
ll dp[N];
int a[105];
int main(){
int n, s, sum=0;
scanf("%d%d", &n, &s);
for(int i=1; i<=n; i++){
scanf("%d", &a[i]);
sum += a[i];
}
dp[0] = 1;
sum -= s;
sum /= 2;
for(int i=1; i<=n; i++){
for(int j=sum; j>=a[i]; j--){
dp[j] += dp[j - a[i]];
dp[j] %= mod;
}
}
printf("%lld\n", dp[sum]);
return 0;
}
题目3 : Target Sum
-
5 3 1 1 1 1 1
样例输出
-
5
描述
There is a sequence of N positive integers A1, A2, ... AN and a target sum S. You need to add a plus or minus operator (+/-) before every integer so that the resulted expression equals to S. Find out the number of such expressions.
Example if the sequence A is [1, 1, 1, 1, 1] and the target sum S is 3. There are 5 valid expressions: -1+1+1+1+1=3, +1-1+1+1+1=3, +1+1-1+1+1=3, +1+1+1-1+1=3 and +1+1+1+1-1=3.
输入
The first line contains 2 integers N and S denoting the number of integers and the target sum.
The second line contains N integers A1, A2, ... AN.
For 80% of the data: 1 <= N <= 10
For 100% of the data: 1 <= N <= 100 1 <= S <= 100000 1 <= Ai <= 1000
输出
The number of valid expressions. The answer may be very large so you only need to output the answer modulo 1000000007.