1. 程式人生 > >2017年上海金馬五校程式設計競賽 Problem C : Count the Number

2017年上海金馬五校程式設計競賽 Problem C : Count the Number

Problem 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

分析

題意:給一組數,每個數字前需要加一個“+”或者一個“-”,最後將全部數求和,計算出各種情況的下總和的值不同的數目。很簡單,時間限制3s,所以直接暴力

程式碼

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdlib>
#include <cstring> #include <cstdio> #include <cmath> using namespace std; int a[22],b[2000000]; int N,sum,sumn1; void counth(int i,queue<int>q) { if(i>=N)///全部數都加上之後計算不同的和的數量 { int zsum; zsum=q.size(); sum=zsum; for(int k=0;k<zsum;k++) { b[k]=q.front(); q.pop(); }///將佇列中的元素存入陣列中 sort(b,b+zsum);///將陣列元素排序用來刪重 for(int k=1;k<zsum;k++) if(b[k]==b[k-1])sum--; return; } sumn1=q.size(); for(int j=0;j<sumn1;j++) { q.push(q.front()+a[i]);///將各個數字的兩種情況都入隊 q.push(q.front()-a[i]); q.pop();///將計算過的總和出隊 } i++; counth(i,q); } int main() { while(~scanf("%d",&N)) { queue<int>q;///定義佇列存放不同情況下的和 for(int k=0;k<N;k++) scanf("%d",&a[k]); q.push(a[0]); q.push(-a[0]);///將第一個數入隊 counth(1,q); printf("%d\n",sum); } }