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 }