Let's define an unambiguous arithmetic expression (UAE) as follows.
- All non-negative integers are UAE's. Integers may have leading zeroes (for example, 0000 and 0010 are considered valid integers).
- If X and Y are two UAE's, then "(X) + (Y)", "(X) - (Y)", "(X) * (Y)", and "(X) / (Y)" (all without the double quotes) are UAE's.
-
If X is an UAE, then " - (X)"
and " + (X)" (both without the double quotes) are UAE's.
You are given a string consisting only of digits ("0" - "9") and characters "-", "+", "*", and "/". Your task is to compute the number of different possible unambiguous arithmetic expressions such that if all brackets (characters "(" and ")") of that unambiguous arithmetic expression are removed, it becomes the input string. Since the answer may be very large, print it modulo 1000003 (106 + 3).
The first line is a non-empty string consisting of digits ('0'-'9') and characters '-', '+', '*', and/or '/'. Its length will not exceed 2000. The line doesn't contain any spaces.
Print a single integer representing the number of different unambiguous arithmetic expressions modulo 1000003 (106 + 3) such that if all its brackets are removed, it becomes equal to the input string (character-by-character).
1+2*3
2
03+-30+40
3
5//4
0
5/0
1
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
100728
For the first example, the two possible unambiguous arithmetic expressions are:
((1) + (2)) * (3) (1) + ((2) * (3))
For the second example, the three possible unambiguous arithmetic expressions are:
(03) + (( - (30)) + (40)) (03) + ( - ((30) + (40))) ((03) + ( - (30))) + (40)
题目大意:这题看上去很花哨,实际上大多都是废话。大致意思就是说,一些数(可以有前导零和正负号)构成的不同的代数式有多少种。
思路:我们先来分析几种不可能的情况,(1)第一位有*或/,这显然;(2)最后一位有符号,显然;(3)连续出现两个符号且第二个符号是*或/,我们思考,若+-和+-挨着,可能造成的情况是加上一个正数或加上一个负数这种情况(因为一个数可以有正负号),而如果第二位是个*/,就一定不可能。
求方案数,一眼就知道是个DP,我们设置状态为f[i]表示处理到前i个符号的方案数,提前预处理处连续两个+-的位置,向后转移,若此处有连续的加减,则方案由j+1向j转移,否则由j向j转移。
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<ctime>
using namespace std;
const int MAXN=2010;
const int Mod=1e6+3;
char s[MAXN];
int f[MAXN][MAXN],g[MAXN][MAXN];
int pos[MAXN];
int main()
{
scanf("%s",s);
int len=strlen(s);
if (s[0]=='*' || s[0]=='/' || s[len-1]<'0' | s[len-1]>'9')
{
cout<<0;
return 0;
}
int num=0;
for (int i=0;i<len;i++)
{
if (s[i]<'0' || s[i]>'9')
{
if (s[i+1]=='*' || s[i+1]=='/')
{
cout<<0;
return 0;
}
else if (s[i+1]=='+' || s[i+1]=='-')
{
pos[num]=1;
}
num++;
}
}
f[0][0]=1;
for (int i=0;i<num;i++)
{
for (int j=0;j<=num;j++)
{
g[i][j]=f[i][j];
if (j)
{
g[i][j]+=g[i][j-1];
}
g[i][j]%=Mod;
}
if (!pos[i])
{
for (int j=0;j<num;j++)
{
f[i+1][j]+=g[i][j+1];
f[i+1][j]%=Mod;
}
}
else
{
for (int j=1;j<num;j++)
{
f[i+1][j]+=g[i][j];
f[i+1][j]%=Mod;
}
}
}
cout<<f[num][0];
return 0;
}
本文介绍了一种算法,用于计算给定字符串能组成的无歧义算术表达式的数量,并提供了一个具体的实现示例。

620

被折叠的 条评论
为什么被折叠?



