Skip to content

Commit 1d0b112

Browse files
authored
Merge pull request #598 from AbhiC7721/devincept
Added SQRBR problem
2 parents e81344a + 017e5fe commit 1d0b112

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*Problem statement => https://www.spoj.com/problems/SQRBR/
2+
You are given:
3+
4+
-> a positive integer n,
5+
-> an integer k, 1<=k<=n,
6+
-> an increasing sequence of k integers 0 < s1 < s2 < ... < sk <= 2n.
7+
What is the number of proper bracket expressions of length 2n with opening brackets appearing in positions s1, s2,...,sk?
8+
*/
9+
10+
11+
#include<bits/stdc++.h>
12+
using namespace std;
13+
14+
15+
typedef string STR;
16+
typedef long long LL;
17+
typedef vector<LL> VLL;
18+
19+
#define all(a) (a).begin(),(a).end()
20+
#define dec(n) cout<<fixed<<setprecision(n);
21+
#define f(i,a,b) for (i = a; i < b; i++)
22+
#define fr(i,a,b) for (i = a; i > b; i--)
23+
#define rep(i,n) for (i = 0 ; i < n; i++)
24+
#define repr(i,n) for (i = n - 1; i >= 0; i--)
25+
#define fsort(a) sort(a.begin(),a.end())
26+
#define rsort(a) sort(a.rbegin(),a.rend())
27+
28+
const LL MOD = 1000000007;
29+
30+
LL sq_brackets(LL n, LL k, VLL pos)
31+
{
32+
vector<bool>h(2*n+1, 0);
33+
LL i;
34+
rep(i, k) h[pos[i]]=1; // hash array ti store the postions where opening bracket is must
35+
// dp array
36+
vector<vector<LL>>dp(2*n+1, vector<LL>(2*n+1, 0));
37+
// first position only one possible combination
38+
dp[0][0] = 1%MOD;
39+
// dp[i][j] represents i positions such that there are j more '[' brackets than ']'
40+
for(LL i=1;i<=2*n;i++)
41+
{
42+
for(LL j=0;j<=2*n;j++)
43+
{
44+
//if that position has an opening bracket
45+
if(h[i])
46+
{
47+
// if diff(j) is not 0 then ith position has '[' hence dp[i][j]=dp[i-1][j-1]
48+
if(j!=0)
49+
dp[i][j] = dp[i-1][j-1]%MOD;
50+
else
51+
dp[i][j]=0; // no possibility if j==0
52+
}
53+
else
54+
{
55+
// both opening and closing brackets possible if h[i]!=1
56+
if(j!=0)
57+
dp[i][j] = (dp[i-1][j-1]%MOD + dp[i-1][j+1]%MOD)%MOD;
58+
else
59+
dp[i][j] = dp[i-1][j+1]%MOD;
60+
}
61+
}
62+
}
63+
return dp[2*n][0];
64+
}
65+
int main()
66+
{
67+
int t=1;
68+
cin>>t;
69+
while(t--)
70+
{
71+
LL n,k,i;
72+
cin>>n>>k;
73+
VLL pos(k);
74+
rep(i,k)
75+
cin>>pos[i];
76+
LL ans = sq_brackets(n, k, pos);
77+
cout<<ans<<"\n";
78+
}
79+
return 0;
80+
}

0 commit comments

Comments
 (0)