EOJ 2832:ZERO(DFS)
2015-09-16 19:43
288 查看
题目链接:http://www.acm.cs.ecnu.edu.cn/problem.php?problemid=2832
题意:给你一个1-n(2≤n≤9)(2 \le n \le 9)的序列,要求在每两个数字中加入’+’,’-‘或者’ ‘(空格),使得整个式子的值为0。按照字典序输出所有的解。
分析:
和UVa的817,基本套用那道题,只是把*改成空格而已。主要思想为DFS进行搜索构造表达式,然后对表达式进行求值即可。
UVa 817题解:/article/11596996.html
代码:
题意:给你一个1-n(2≤n≤9)(2 \le n \le 9)的序列,要求在每两个数字中加入’+’,’-‘或者’ ‘(空格),使得整个式子的值为0。按照字典序输出所有的解。
分析:
和UVa的817,基本套用那道题,只是把*改成空格而已。主要思想为DFS进行搜索构造表达式,然后对表达式进行求值即可。
UVa 817题解:/article/11596996.html
代码:
#include <iostream> #include <algorithm> #include <fstream> #include <string> #include <cstring> #include <vector> #include <queue> #include <cmath> #include <cctype> #include <stack> #include <set> using namespace std; const int maxn = 20 + 5; const char op[] = {"+- "}; int T, n; string s; set< string > ans; int cmp(char x, char y) { if ((x == '-' || x == '+') && (y == ' ')) return -1; return 1; } int calc(int x, int y, char op) { switch(op) { case '+': return x + y; case '-': return x - y; case ' ': return x * 10 + y; } } void update(const string& ss) { stack< int > num; stack< char > opp; int len = ss.size(); for (int i = 0; i < len; ++i) { int tmp = 0, pos = i; while (pos < len && isdigit(ss[pos])) { tmp = tmp * 10 + ss[pos] - '0'; ++pos; } if (pos - i > 1 && ss[i] == '0') return; num.push(tmp); if (pos < len) { if (opp.size() == 0) opp.push(ss[pos]); else { if (cmp(opp.top(), ss[pos]) < 0) opp.push(ss[pos]); else { while (!opp.empty() && cmp(opp.top(), ss[pos]) >= 0) { int yy = num.top(); num.pop(); int xx = num.top(); num.pop(); char OP = opp.top(); opp.pop(); num.push(calc(xx, yy, OP)); } opp.push(ss[pos]); } } } i = pos; } while (!opp.empty()) { int yy = num.top(); num.pop(); int xx = num.top(); num.pop(); char OP = opp.top(); opp.pop(); num.push(calc(xx, yy, OP)); } if (num.top() == 0) ans.insert(ss); } void DFS(int pos, int deep, int limit, string ss) { if (deep == limit) { update(ss); return; } int len = ss.size(); if (len - pos - 1 < limit - deep) return; for (int i = pos + 1; i < len; ++i) { for (int j = 0; j < 3; ++j) { string tmp = ss; tmp.insert(i, 1, op[j]); DFS(i + 1, deep + 1, limit, tmp); } } } int main() { scanf("%d", &T); for (int C = 0; C < T; ++C) { if (C) printf("\n"); scanf("%d", &n); s = ""; for (int i = 1; i <= n; ++i) s += (char)(i + '0'); ans.clear(); DFS(0, 0, n - 1, s); for (set< string >::iterator it = ans.begin(); it != ans.end(); ++it) cout << *it << "\n"; } return 0; }
相关文章推荐
- MySQL中的?加关键字查询命令用法
- 第七天 :Before -- CMD
- 前端性能优化(五)
- 2015最火的十大开源项目,是个程序员你就该看看!
- (小结)第二章:基本程序设计
- 3.5 fdopen()和fileno()函数 http://book.2cto.com/201212/11763.html
- skia bitmap shader
- LA-3026 - Period-MP算法-失配函数-寻找循环节 (kmp)
- 去除img图片之间的空隙css样式
- 移动,联通,电信手机都属于什么频段?
- redis+PHP实现的一个优先级去重队列
- iOS中FMDB简介
- 解决移进/规约冲突
- HDOJ 2896 病毒侵袭
- dup函数
- 111
- Objective-C Runtime 运行时之五:协议与分类
- 网络七层架构
- 网络七层架构
- android studio Error:Execution failed for task ':app:dexDebug'.解决