Abridged problem statement
Given the number of left and right parenthesis, output the maximum number of balanced substrings in all possible subsets of the string.Constraints
1 ≤ T ≤ 100.
Small dataset
0 ≤ L ≤ 20.0 ≤ R ≤ 20.
1 ≤ L + R ≤ 20.
Large dataset
0 ≤ L ≤ 105.0 ≤ R ≤ 105.
1 ≤ L + R ≤ 105.
Approach
Let us try to obtain the answer manually for certain cases.
Case 1:
L = 1, R = 1
We can form only ( ) string which conatains 1 balanced substring.
Case 2:
L = 2, R = 2
We can form ( ) ( ) which contains 3 balanced substrings, i.e. index 1 to 2, index 3 to 4, index 1 to 4.
Case 3:
L = 3, R = 3
We can form ( ) ( ) ( ) which contains 6 balanced substrings, i.e. with indices 1 to 2, 3 to 4, 5 to 6, 1 to 4, 3 to 6, 1 to 6.
Case 4:
L = 4, R = 4
We can obtain 10 balanced substrings from ( ) ( ) ( ) ( ).
Hence we obtain the series 1, 3, 6, 10, ...
This forms the set of triangular numbers: where
a(n) = binomial(n+1,2) = n(n+1)/2
Code
#include <iostream> #include <fstream> #include <iomanip> using namespace std; int main(){ freopen("inputlarge.in", "r", stdin); freopen("outputlarge.txt", "w", stdout); long t, l, r, n; cin>>t; for(int cases = 1; cases <= t; cases++){ cin>>l>>r; n = min(l,r); cout<<"Case #"<<cases<<": "<<fixed<< setprecision(0)<<1.0 * n * (n+1) / 2<<endl; } return 0; }
Comments
Post a Comment