HDU--5151(区间DP)

2014-12-27 23:34:16

思路:用dp[i][j]表示处理区间[i,j]的方案数,然后枚举区间[i,j]中最后坐下的人是k。

  转移方程:dp[i][j] = Sima(dp[i][k - 1] * dp[k + 1][j] * C(j - i , k - i)) (i <= k <= j)

  之所以乘以组合数是因为:看成给人安排座位,要在j - i步中安排调除k以外的j - i个人,选k - i步安排左边的人,另外j - k步安排右边的人。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cmath>
 5 #include <vector>
 6 #include <map>
 7 #include <set>
 8 #include <stack>
 9 #include <queue>
10 #include <iostream>
11 #include <algorithm>
12 using namespace std;
13 #define lp (p << 1)
14 #define rp (p << 1|1)
15 #define getmid(l,r) (l + (r - l) / 2)
16 #define MP(a,b) make_pair(a,b)
17 typedef long long ll;
18 typedef unsigned long long ull;
19 const int INF = 1 << 30;
20 const ll mod = 1000000007;
21 
22 int N,val[110];
23 ll dp[110][110],c[210][210];
24 
25 int main(){
26     for(int i = 0; i <= 200; ++i){
27         c[i][0] = c[i][i] = 1;
28         for(int j = 1; j < i; ++j){
29             c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
30         }
31     }
32     while(scanf("%d",&N) != EOF){
33         for(int i = 1; i <= N; ++i)
34             scanf("%d",&val[i]);
35         memset(dp,0,sizeof(dp));
36         for(int i = 1; i <= N; ++i)
37             dp[i][i] = dp[i][i - 1] = dp[i + 1][i] = 1;
38         for(int len = 1; len <= N; ++len){
39             for(int i = 1; i + len <= N; ++i){
40                 int j = i + len;
41                 for(int k = i; k <= j; ++k) if(k == i || k == j || (val[k - 1] == val[k + 1])){
42                     dp[i][j] = (dp[i][j] + ((dp[i][k - 1] * dp[k + 1][j]) % mod * c[j - i][k - i]) % mod) % mod;
43                 }
44             }
45         }
46         printf("%I64d\n",dp[1][N]);
47     }
48     return 0;
49 }

 

posted @ 2014-12-27 23:40  Naturain  阅读(219)  评论(0编辑  收藏  举报