您的位置:首页 > 产品设计 > UI/UE

UESTC 2016 Summer Training #1 Div.2 L - Plus or Minus (A) dfs

2016-07-12 21:32 417 查看
L - Plus or Minus (A)
Time Limit:1000MS Memory Limit:262144KB 64bit IO Format:%I64d
& %I64u
Submit Status Practice Gym
100989L

Description

standard input/output

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: A1oA2oA3o ... oAn = 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.

Sample Input

Input
7
1 + 1 - 4 - 4 - 4 - 2 - 2


Output
3


Input
35 + 3 - 7


Output
-1


Source

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=121539#problem/L

My Solution

dfs就好, 好久没用写dfs了,简单dfs还是Debug了好长时间, 尴尬⊙﹏⊙‖∣

记得把那些转移的东西写在参数里

读入char类型, 记得看看要不要用getchar吸掉换行空格什么的

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
typedef long long LL;
const int maxn = 28;
int val[maxn];
char plusmi[maxn];
int ans, n;
void dfs(int k, int sum, int q)
{
if(k == n){
if(sum == 0) ans = min(ans, q);
return;
}

for(int i = 0; i < 2; i++){
if(i == 0){
if(plusmi[k] == '-') dfs(k+1, sum + val[k], q + 1);
else dfs(k+1, sum + val[k], q);
}
else{
if(plusmi[k] == '+') dfs(k+1, sum - val[k], q + 1);
else dfs(k+1, sum - val[k], q);
}
}
}

int main()
{
#ifdef LOCAL
freopen("a.txt", "r", stdin);
//freopen("b.txt", "w", stdout);
int T = 2;
while(T--){
#endif // LOCAL
scanf("%d", &n);
scanf("%d", &val[0]);
for(int i = 1; i < n; i++){

getchar();
scanf("%c", &plusmi[i]);
scanf("%d", &val[i]);

}
/*
printf("%d", val[0]);
for(int i = 1; i < n; i++)
printf("%c%d",plusmi[i] , val[i]);
*/
ans = 1000;
dfs(1,val[0], 0);

if(ans != 1000) printf("%d", ans);
else printf("-1");

#ifdef LOCAL
printf("\n");
}
#endif // LOCAL
return 0;
}


Thank you!

------from ProLights
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: