您的位置:首页 > 其它

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

代码:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: