Gym - 100989L dfs

Time limit

1000 ms

Memory limit

262144 kB

题目描述:

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

 

 

简单dfs

 

 

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

int ans=30,flag=0,al[25],n;

 

char bl;
void dfs(int x,int y,int dfst,int f)

 

// x(深度)  y(是否改变符号(1为不变)(-1为改变))  dfst(为dfs到x深度时的和)  f(记录符号改变的次数)

 

//因为只需要得到最后一组的数据  所以使用dfst和f来记录前x个数总和和前x次符号改变次数的总和

//不需要使用数组来生成线段树记录每一次dfs的结果
{
    dfst=al[x]*y+dfst;
    if(y==-1)
    {
        f=f+1;
    }
    else
    {
        f=f;
    }
    if(x==n)
    {
        if(dfst==0)
        {
            flag=1;
            ans=min(ans,f);
        }
        return ;
    }
    dfs(x+1,1,dfst,f);//符号不变
    dfs(x+1,-1,dfst,f);//符号改变
}
int main()
{
    cin>>n;
    for(int n1=1;n1<=n;n1++)
    {
        if(n1==1)
        {
            cin>>al[n1];
        }
        else
        {
            getchar();
            cin>>bl;
            getchar();
            cin>>al[n1];
            if(bl=='-')
            {
                al[n1]=-al[n1];
            }
        }
    }
    dfs(1,1,0,0);
    if(flag==1)//flag判断能否得到和为0
    {
        cout<<ans<<endl;
    }
    else
    {
        cout<<-1<<endl;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值