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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyxeainn/article/details/72853393


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的规模不超过20(问题规模比较小),接下来一行给出N个数字,然后我们可以在任何一个数字前面放置+或-号。然后计算出一个值。

问由这组数经过不同的加减组合能得到多少种不同的答案。

解题思路:

这个也是简单题,题目时间给了3秒,问题规模不超过20也不大,直接暴力,dfs + map(用来映射某个答案出没出现过)


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

long long a[25];
map<long long,int>m;
long long ans;
int n;
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 = 1; i <= n; i++)
            scanf("%d",&a[i]);
        m.clear();
        ans = 0;
        dfs(0,1);
        printf("%d\n",ans);
    }
    return 0;
}



阅读更多

没有更多推荐了,返回首页