题意:有一个只有’(‘和’)’的串,可以随意的删除随意多个位置的符号,现在问能构成((((((…((()))))….))))))这种对称的情况有多少种,保证中间对称,左边为’(‘右边为’)’。
析:通过枚举 ‘(’ 来计算有多少种情况,假设 第 i 个括号前面有 n 个 '(',右边有 m 个 ')',那么总共就有 sigma(1, n, C(n-1, i-1)*C(m, i)),其中 1,n 表示从上下限。。
然后这样算的话就是 n 方的复杂度,会超时,再利用范德蒙恒等式(不会的请点击:http://www.cnblogs.com/dwtfukgv/articles/7120297.html)进行化简,可得C(n+m-1, n),
这样就去掉那个求和,复杂度只有 O(n)了,计算组合数时要用逆元。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <sstream> #define debug() puts("++++"); #define gcd(a, b) __gcd(a, b) #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const LL LNF = 1e16; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 300000 + 10; const int mod = 1000000007; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } LL inv[maxn]; LL f[maxn], fact[maxn]; int l[maxn], r[maxn]; char s[maxn]; LL C(int n, int m){ return fact[n] * f[m] % mod * f[n-m] % mod; } int main(){ f[0] = 1; inv[1] = f[1] = fact[1] = 1; for(int i = 2; i < maxn; ++i){ inv[i] = (mod - mod/i) * inv[mod%i] % mod; f[i] = f[i-1] * inv[i] % mod; fact[i] = fact[i-1] * i % mod; } cin >> s+1; n = strlen(s+1); vector<int> v; for(int i = 1; i <= n; ++i){ l[i] = s[i] == '(' ? l[i-1]+1 : l[i-1]; if(s[i] == '(') v.push_back(i); } for(int i = n; i > 0; --i) r[i] = s[i] == ')' ? r[i+1]+1 : r[i+1]; LL ans = 0; for(int i = 0; i < v.size(); ++i){ int n = l[v[i]]; int m = r[v[i]]; ans = (ans + C(m+n-1, n)) % mod; } cout << ans << endl; return 0; }