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.

扫描二维码关注公众号,回复: 2601164 查看本文章

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;
    }
}

猜你喜欢

转载自blog.csdn.net/ecjtu_17_TY/article/details/80937897