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

本文探讨了一道算法题目,该题目要求对于给定的一组整数,通过在其前后添加正负号并允许重新排列这些数来构造不同的数学表达式,并最终计算得到的不同结果的数量。文章提供了详细的解题思路及实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题目的意思就是给定20个以内int范围的数,在每个数前面添加加减符号(相当于正负号),问一种有多少种和。

一开始我是想的找规律,有几个不同的数就先算2的几次方,然而重复出现次数的就当做+1,,,如果有0的就不做计算,,然后提交,,,果然错了,然后我想了想,有负数,应该算绝对值相同的去重,再来,还是不过。。。。哎,看来找规律找不出来了。。

然后就注意到题目时间限制3S,,,挺长的呢,就想直接暴力把所有情况都算出来,再去重应该也能过。果然,过了。用的递归,搜索应该也行的。

#include<iostream>
#include<stdio.h>
#include<map>
using namespace std;
int ch[25];
int count1;
int n;
map<int,int> M;
void DFS(int sum,int k)
{
    if(k==n-1)
    {
        M[sum+ch[k+1]]++;
        if(M[sum+ch[k+1]]==1)
            count1++;
        M[sum-ch[k+1]]++;
        if(M[sum-ch[k+1]]==1)
            count1++;
        return;
    }
    DFS(sum+ch[k+1],k+1);
    DFS(sum-ch[k+1],k+1);
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        M.clear();
        count1=0;
        for(int i=1;i<=n;i++)
            scanf("%d",&ch[i]);
        DFS(0,0);
        printf("%d\n",count1);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值