2017上海金马五校程序设计竞赛 C :Count the Number

本文介绍了一道编程题目,任务是对于给定的一组整数,通过在其前面添加正负号并重新排列来构造不同的表达式,计算每种可能组合的结果,并统计不同结果的数量。

Time Limit: 3 s

Description

Given n numbers, your task is to insert '+' or '-' in front of each number to construct expressions. Note that the position of numbers can be also changed.

You can calculate a result for each expression. Please count the number of distinct results and output it.

 Input


There are several cases.
For each test case, the first line contains an integer n (1 ≤ n ≤ 20), and the second line contains n integers a1,a2, ... ,an(-1,000,000,000 ≤ ai ≤ 1,000,000,000).

Output

For each test case, output one line with the number of distinct results

Sample Input

2
1 2
3
1 3 5

 Sample Output

4
8
本题题意:
这题说的是第一行给你一个n,接下来一行给你n个数,可以在这n 个数前边加“+”或者“-”,计算这些数的和,输出有几种不同的和。
解题思路:
因为数据比较小,直接暴力深搜就可以。

代码:
#include <iostream>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;
int a[25];
map <int,int> M;
int n,ans;
void dfs(int sum,int i)
{
    if(i==n+1)
    {
        if(M[sum]==0)///如果没有出现过
        {
            M[sum]=1;
            ans++;
        }
        return;
    }
    dfs(sum+a[i],i+1);
    dfs(sum-a[i],i+1);
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=0; i<n; i++)
            scanf("%d",&a[i]);
        M.clear();
        ans=0;
        dfs(0,0);
        printf("%d\n",ans);
    }
    return 0;
}


Output

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值