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

Problem C : Count the Number


 (Out of Contest)

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个数,每个数前面都可以插入一个运算符'+'或'-',要求得出最终的答案有多少种。

解题思路:

由于给的时间比较大,数据量小,可以直接暴力把所有种方案都算出来然后找出不同的方案有多少种。因为set有去重的功能,所以我的方法是用dfs+set来得出最后的方案结果。

代码如下:

#include<iostream>
#include<algorithm>
#include<set>
#include<stdio.h>
#include<string.h>
using namespace std;

long long int a[25];
set <long long int> S;
long long int ans;
int n;
void dfs(int sum,int i)
{
    if(i == n+1)
    {
        S.insert(sum);
        return;
    }
    dfs(sum+a[i],i+1);//加法
    dfs(sum-a[i],i+1);//减法
}
int main()
{
    while(~scanf("%d",&n))
    {
        S.clear();//清除S集合
        for(int i = 1; i <= n; i++)
            scanf("%lld",&a[i]);
        ans = 0;
        dfs(0,0);
        printf("%d\n",S.size());
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值