Gym - 100989L

AbdelKader enjoys math. He feels very frustrated whenever he sees an incorrect equation and so he tries to make it correct as quickly as possible!

Given an equation of the form: A1 o A2 o A3 o ... o An  =  0, where o is either + or -. Your task is to help AbdelKader find the minimum number of changes to the operators + and -, such that the equation becomes correct.

You are allowed to replace any number of pluses with minuses, and any number of minuses with pluses.

Input

The first line of input contains an integer N (2 ≤ N ≤ 20), the number of terms in the equation.

The second line contains N integers separated by a plus + or a minus -, each value is between 1 and 108.

Values and operators are separated by a single space.

Output

If it is impossible to make the equation correct by replacing operators, print  - 1, otherwise print the minimum number of needed changes.

题意:改变+或-使等式为0,求最小改变次数。

思路,dfs枚举所有情况,当与当前符号不符时修改次数+1,每次走到递归出口时更新最小的修改次数,如果minn变量的初值未改变就说明等式不可能成立,当和为奇数时等式一定不能成立。

代码如下

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 int a[21];
 6 char b[21];
 7 int m;
 8 long long int minn=999999999;
 9 void dfs(int sum,int t,int s)
10 {
11     if(t==m-1)
12     {
13         if(sum==0) 
14         {
15             if(s<minn)
16             minn=s;
17         }
18         return;
19     }
20     if(b[t+1]=='+')
21     {
22         dfs(sum+a[t+1],t+1,s);
23         dfs(sum-a[t+1],t+1,s+1);
24     }
25     if(b[t+1]=='-')
26     {
27         dfs(sum+a[t+1],t+1,s+1);
28         dfs(sum-a[t+1],t+1,s);
29     }
30 }
31 int main()
32 {
33     cin>>m;
34     long long sum=0;
35     cin>>a[0];
36     sum=a[0];
37     for(int i=1;i<m;i++)
38     {
39         cin>>b[i];
40         getchar();
41         cin>>a[i];
42         getchar();
43         sum+=a[i];
44     }
45     if(sum%2)
46     cout<<-1<<endl;
47     else
48     {
49         dfs(a[0],0,0);
50         if(minn!=999999999)
51         cout<<minn<<endl;
52         else
53         cout<<-1<<endl;
54     }
55     return 0;
56 }

 

  

转载于:https://www.cnblogs.com/spongeb0b/p/9272492.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值