• Gym-100989L(搜索)


    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

    题目大意:n个数字之间有n-1个运算符+或-,通过改变运算符使得值为0。

    解题思路:可以看到n范围很小,所以可以采用暴力搜索。

    代码如下:

    #include<stdio.h>
    #include<algorithm>
    using namespace std;
    
    int n;
    int a[50];
    int ans=-1;
    
    void dfs(int c,int cnt,int f)
    {
        if(c==n+1&&cnt==0)
        {
            if(ans==-1) ans=f;
            else ans=min(ans,f);
        }
        if(c==n+1) return ;
        dfs(c+1,cnt+a[c],f);
        dfs(c+1,cnt-a[c],f+1);
    }
    
    void solve()
    {
        dfs(2,a[1],0);
        printf("%d
    ",ans);
    }
    
    int main()
    {
        char ch[5];
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            //printf("...
    ");
            if(i==1)
            {
                scanf("%d",&a[i]);
            }
            else
            {
                scanf("%s%d",&ch,&a[i]);
                if(ch[0]=='-')
                {
                    a[i]=-a[i];
                }
            }
        }
        solve();
        return 0;
    }
  • 相关阅读:
    HTTPD之五---HTTP协议、相关工具及状态码
    HTTPD之四----实现HTTPD正向代理与反向代理
    第十三周---DNS原理、实现智能DNS及源码编译mariadb数据库
    DNS之五----实现智能DNS
    sqoop 导入增量数据到hive
    Hadoop 二次排序
    Spark foreachpartiton和mappartition的异同
    hadoop 实现多文件输出
    spark 实现多文件输出
    Scala 中 call by name & call by value 的区别
  • 原文地址:https://www.cnblogs.com/noback-go/p/11157598.html
Copyright © 2020-2023  润新知