您的位置:首页 > 其它

hdu 5396 Expression(区间dp)

2015-08-18 23:38 253 查看
[align=left]Problem Description[/align]
Teacher Mai has n numbers a1,a2,⋯,anand n−1 operators("+", "-" or "*")op1,op2,⋯,opn−1, which are arranged in the form a1 op1 a2 op2 a3 ⋯ an.
He wants to erase numbers one by one. In i-th round, there are n+1−i numbers remained. He can erase two adjacent numbers and the operator between them, and then put a new number (derived from this one operation) in this position. After n−1 rounds, there is the only one number remained. The result of this sequence of operations is the last number remained.
He wants to know the sum of results of all different sequences of operations. Two sequences of operations are considered different if and only if in one round he chooses different numbers.
For example, a possible sequence of operations for "1+4∗6−8∗3" is 1+4∗6−8∗3→1+4∗(−2)∗3→1+(−8)∗3→(−7)∗3→−21.

[align=left]Input[/align]
There are multiple test cases.
For each test case, the first line contains one number n(2≤n≤100).
The second line contains n integers a1,a2,⋯,an(0≤ai≤109).
The third line contains a string with length n−1 consisting "+","-" and "*", which represents the operator sequence.

[align=left]Output[/align]
For each test case print the answer modulo 109+7.

[align=left]Sample Input[/align]

3
3 2 1
-+
5
1 4 6 8 3
+*-*

[align=left]Sample Output[/align]

2
999999689

Hint

Two numbers are considered different when they are in different positions.

[align=left]Author[/align]
xudyh

2015 Multi-University Training Contest 9

设d[i][j] 代表i~j的答案。区间DP枚举(i, j)区间的断点,如果断点处的操作符是‘*’,那么该区间的答案可以直接加上d[i][k] * d[k+1][j],因为乘法分配律可以保证所有的答案都会乘起来。如果是加法,需要加的 就是 左边的答案 乘 右边操作数的阶乘 加上 右边的答案乘左边操作数的阶乘,最后要确定左边操作和右边操作的顺序 因为每个答案里是统计了该区间所有的阶乘情况,因此每一个左边已确定的顺序和右边已确定的顺序需要排列组合一下。比如:左边有3个操作数+-*,右边有2个操作符+-,当已经确定了他们各自的顺序,假设左边算-*+,右边+-,这个顺序已经固定,现在有五个操作符需要操作,我需要选择三个位置给左边的操作符-*+,那么右边的两个操作符自然就对应他们相应的位置。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 106
#define MOD 1000000007
#define ll long long
ll A
={1};
ll C

={1};
ll dp

;
char op
;
void init()
{
A[0]=1;
for(ll i=1;i<N;i++)
A[i]=A[i-1]*i%MOD;

for(ll i=1;i<N;i++)
C[i][i]=C[i][0]=1;
for(int i=1;i<N;i++)
{
for(ll j=1;j<i;j++)
C[i][j]=(C[i-1][j-1]+C[i-1][j])%MOD;
}
}
int main()
{
init();
ll n;
while(scanf("%I64d",&n)==1)
{
memset(dp,0,sizeof(dp));
for(ll i=0;i<n;i++)
{
scanf("%I64d",&dp[i][i]);
}
scanf("%s",op);

for(ll len=1;len<=n;len++)
{
for(ll i=0;i+len<n;i++)
{
ll j=i+len;
for(ll k=i;k<j;k++)
{
ll tmp;
if(op[k]=='+')
{
tmp=(dp[i][k]*A[j-k-1]+dp[k+1][j]*A[k-i])%MOD;
}
else if(op[k]=='-')
{
tmp=(dp[i][k]*A[j-k-1]-dp[k+1][j]*A[k-i])%MOD;
tmp=(tmp+MOD)%MOD;
}
else
{
tmp=(dp[i][k]*dp[k+1][j])%MOD;
}
tmp=tmp*C[j-i-1][k-i]%MOD;
dp[i][j]=(dp[i][j]+tmp+MOD)%MOD;
}
}
}
printf("%I64d\n",dp[0][n-1]);
}
return 0;
}


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