给定一个数字n,构造一个长度为2n的括号序列,每个‘( ’都能在其右边找到唯一对应的‘ )’则为合法序列,根据所有合法情况建一棵树,现有一个边集S满足集合内所有边均无公共点,求该边集的最大值(对1e9+7取模)
:用dp[i][j][k]表示从 剩余i个左括号,j个右括号往下走能得到的max,k=0表示这个点与父节点的边不选,1表示要选。
当i==j时,只能选用左括号,
dp[i][j][0]=dp[i-1][j][1]+1
dp[i][j][1]=dp[i-1][j][0]
j>i时,两边都可以选,
dp[i][j][0] = 1 + dp[i - 1][j][1] + dp[i][j - 1][0] //选左右答案是一样的,我有一个绝妙的证明方法,但是这里太小写不下
dp[i][j][1] = dp[i - 1][j][0] + dp[i][j - 1][0]
AC代码:
```cpp
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <cmath>
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define pd(n) printf("%d\n", (n))
#define pdd(n,m) printf("%d %d", n, m)
#define pld(n) printf("%lld\n", n)
#define pldd(n,m) printf("%lld %lld\n", n, m)
#define sld(n) scanf("%lld",&n)
#define sldd(n,m) scanf("%lld%lld",&n,&m)
#define slddd(n,m,k) scanf("%lld%lld%lld",&n,&m,&k)
#define sf(n) scanf("%lf",&n)
#define sff(n,m) scanf("%lf%lf",&n,&m)
#define sfff(n,m,k) scanf("%lf%lf%lf",&n,&m,&k)
#define ss(str) scanf("%s",str)
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,a,n) for(int i=n;i>=a;i--)
#define mem(a,n) memset(a, n, sizeof(a))
#define debug(x) cout << #x << ": " << x << endl
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mod(x) ((x)%MOD)
#define gcd(a,b) __gcd(a,b)
#define lowbit(x) (x&-x)
typedef pair<int,int> PII;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const int MOD = 1e9 + 7;
const double eps = 1e-9;
const int maxn = 3e5 + 5;
const int INF = 0x3f3f3f3f;
const long long inf=1e18+5;
inline int read()
{
int ret = 0, sgn = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-')
sgn = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
ret = ret*10 + ch - '0';
ch = getchar();
}
return ret*sgn;
}
inline void Out(int a) //Êä³öÍâ¹Ò
{
if(a>9)
Out(a/10);
putchar(a%10+'0');
}
int qpow(int m, int k, int mod)
{
int res = 1, t = m;
while (k)
{
if (k&1)
res = res * t % mod;
t = t * t % mod;
k >>= 1;
}
return res;
}
ll gcd(ll a,ll b)
{
return b==0?a : gcd(b,a%b);
}
int n;
int i,j,k;
int dp[1004][1004][2];
int main()
{
scanf("%d",&n);
memset(dp, 0, sizeof dp );
for(i=0; i<=n; ++i)
{
dp[0][i][1]=i/2;
dp[0][i][0]=(i+1)/2;
}
for(i=1; i<=n; ++i)
{
for(j=i; j<=n; ++j)
{
if(i==j)
{
dp[i][j][0]=(dp[i-1][j][1]+1)%MOD;
dp[i][j][1]=(dp[i-1][j][0])%MOD;
}
else
{
dp[i][j][0]=(1+dp[i-1][j][1]+dp[i][j-1][0])%MOD;
dp[i][j][1]=(dp[i-1][j][0]+dp[i][j-1][0])%MOD;
}
}
}
printf("%d\n",dp[n][n][0]);
return 0;
}