dfs 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.

Examples

Input
7
1 + 1 - 4 - 4 - 4 - 2 - 2
Output
3
Input
3
5 + 3 - 7
Output
-1



题目翻译:一串数字改变其的符号,让sum为0,输出最小的改变次数,不存在则输出-1


运用算法DFS


ac代码:


#include<iostream>
using namespace std;
int a[25],n,ans;
void dfs(int index,int sum,int c)
{
  if (index==n+1){
    if (sum==0){
      ans=ans<c?ans:c;
    }
  return ;
  }
  int j;
  for (j=0;j<2;j++){      //只存在 + 或者是 - 两种情况
    if (j==0){
      if (a[index]<0)
        dfs(index+1,sum-a[index],c+1);
    else
      dfs(index+1,sum+a[index],c);
    }
    else if (a[index]<0)
      dfs(index+1,sum+a[index],c);
    else
      dfs(index+1,sum-a[index],c+1);
  }
return ;

}
int main()
{
  //scanf("%d",&n);
  char op;
  int i,j;
  ans=99999999;
  cin>>n;
  for (i=1;i<=n;i++){
    if (i==1)
      scanf("%d",&a[i]);
    else{
      scanf(" %c %d",&op,&a[i]);
      if (op=='-')
        a[i]=-a[i];
     }
  }
  dfs(2,a[1],0);
   if (ans==99999999)
    cout<<"-1\n";
  else
    cout<<ans<<endl;
  return 0;
}

转载于:https://www.cnblogs.com/q1204675546/p/9272789.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值