【hihoCoder太阁最新面经算法竞赛13 C】【01背包】Target Sum【给一个序列在序列中添加+或者-,使得运算结果为s,求方法数】

传送门: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

时间限制: 10000ms
单点时限: 1000ms
内存限制: 256MB

描述

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.

样例输入
5 3
1 1 1 1 1
样例输出
5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值