链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
题目描述
Seventeen is a game where players try to construct an equation that evaluates to 17 using operators +-* and parentheses (,) and using each of the given numbers exactly once.
Construct an equation using integers from 111 to nnn exactly once with the value of 17.
输入描述:
The input contains one integer nnn (1≤n≤501 \le n \le 501≤n≤50).
输出描述:
If there is no solution, output −1. Otherwise, output an expression consisting of +, -, *, (, and ). The length of the expression should not exceed 1000 characters.
示例1
输入
复制10
10
输出
复制1+2+3+4+5+6+7+8-9-10
1+2+3+4+5+6+7+8-9-10
说明
The following expression are considered right, too.
-10+1+2+3+4+5+6+7+8-9
((-10+1))+2+3+4+5+6+7+8-9
(-10+1)+2+3+4+5+6+7+8-9
题目意思是给出n,你要使用1到n之中的数字,并用+ , - , *,(,)符号讲他们连接起来,使他们最后的答案等于17.
这一题有一个思路是我的队友写出来的,他使用的是dfs穷举的思想,将n 大于6的情况穷举出答案等于17的式子。
还有一个是8以后的数字x都可以由x - 4得到,比如,4 是(1 + 4) * 3 + 2,8就可以是(1 + 4)*3 + 2 +5 - 6 - 7 + 8,最后还是17,得到转移方程:s[x] = s[x - 4] + (x - 3) - (x - 2) - (x - 1) + x;
代码:
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
#define ll long long
const int N = 1e3 + 10;
string s[N];
int main()
{
ll n;
cin >> n;
s[4] = "(1+4)*3+2";
s[5] = "1*2*5+3+4";
s[6] = "1-2+3+4+5+6";
s[7] = "-3+4+5+6+7-1*2";
if (n <= 3)
{
cout << -1 << '\n';
}
else if (n == 4)
{
cout << s[4] << '\n';
}
else if (n == 5)
{
cout << s[5] << '\n';
}
else if (n == 6)
{
cout << s[6] << '\n';
}
else if (n == 7)
{
cout << s[7] << '\n';
}
else
{
ll m = 8;
while (m <= n)
{
s[m] = s[m - 4];
s[m] += '+';
if(m - 3 <= 9)s[m] += m - 3 + '0';
else
{
string p = "";
ll xx = m - 3;
while (xx)
{
ll x = xx % 10;
p += x + '0';
xx /= 10;
}
reverse(p.begin(), p.end());
s[m] += p;
}
s[m] += '-';
if (m - 2 <= 9)s[m] += m - 2 + '0';
else
{
string p = "";
ll xx = m - 2;
while (xx)
{
ll x = xx % 10;
p += x + '0';
xx /= 10;
}
reverse(p.begin(), p.end());
s[m] += p;
}
s[m] += '-';
if (m - 1 <= 9)s[m] += m - 1 + '0';
else
{
string p = "";
ll xx = m - 1;
while (xx)
{
ll x = xx % 10;
p += x + '0';
xx /= 10;
}
reverse(p.begin(), p.end());
s[m] += p;
}
s[m] += '+';
if (m <= 9)s[m] += m + '0';
else
{
string p = "";
ll xx = m;
while (xx)
{
ll x = xx % 10;
p += x + '0';
xx /= 10;
}
reverse(p.begin(), p.end());
s[m] += p;
}
m++;
}
cout << s[n] << '\n';
}
return 0;
}