随笔 - 346,  文章 - 0,  评论 - 39,  阅读 - 26万

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个数字,然后我们可以在任何一个数字前面放置+或-号。然后计算出一个值。

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

由于问题的规模比较小,直接暴力就可以过,深搜到最后一个数后,肯它得出的答案有没有出现过(用一个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,0);
        printf("%d\n",ans);
    }
    return 0;
}
posted on   渡……  阅读(231)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示