Parentheses Matrix
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1418 Accepted Submission(s): 524
Special Judge
Problem Description
A parentheses matrix is a matrix where every element is either '(' or ')'. We define the goodness of a parentheses matrix as the number of balanced rows (from left to right) and columns (from up to down). Note that:
- an empty sequence is balanced;
- if A is balanced, then (A) is also balanced;
- if A and B are balanced, then AB is also balanced.
For example, the following parentheses matrix is a 2×4 matrix with goodness 3, because the second row, the second column and the fourth column are balanced:
)()(
()()
Now, give you the width and the height of the matrix, please construct a parentheses matrix with maximum goodness.
Input
The first line of input is a single integer T (1≤T≤50), the number of test cases.
Each test case is a single line of two integers h,w (1≤h,w≤200), the height and the width of the matrix, respectively.
Output
For each test case, display h lines, denoting the parentheses matrix you construct. Each line should contain exactly w characters, and each character should be either '(' or ')'. If multiple solutions exist, you may print any of them.
Sample Input
3
1 1
2 2
2 3
Sample Output
(
()
)(
(((
)))
Source
2018 Multi-University Training Contest 8
当 n 和 m 中至少有一个是奇数时,构造的方法是显然的。下面仅讨论n 和 m 都是偶数的情况。
当 n = 2 或 m = 2 的时候 匹配数为 n + m - 2
当 n = 4 或 m = 4 的时候 匹配数为 n + m - 3
其余情况匹配数为 n + m - 4
n = 4的时候可以这么构造
((((((
)))(((
((()))
))))))
m = 4 的时候可以这么构造
()()
()()
()()
(())
(())
(())
其余情况时,可以如下构造:
(保证左边界和上边界是左括号,右边界和下边界是右括号)
((((((((
()()()()
(()()())
()()()()
(()()())
))))))))
匹配数是 n+m−4。
#include <iostream>
using namespace std;
typedef long long ll;
int main()
{
int T,n,m;
cin>>T;
while(T--)
{
cin>>n>>m;
if(n%2==1)
{
for(int i=1;i<=n;i++)
{
for (int j=1;j<=m;j++)
{
if (j%2==1)
cout<<"(";
else
cout<<")";
}
cout<<endl;
}
}
else if(m%2==1)
{
for(int i=1;i<=n;i++)
{
for (int j=1;j<=m;j++)
{
if (i%2==1)
cout<<"(";
else
cout<<")";
}
cout<<endl;
}
}
else
{
if(n==2)
{
for(int j=1; j<=m; j++)
cout<<"(";
cout<<endl;
for(int j=1; j<=m; j++)
cout<<")";
cout<<endl;
}
else if(n==4)
{
for(int j=1; j<=m; j++)
cout<<"(";
cout<<endl;
for(int j=1; j<=m; j++)
{
if(j<=m/2)
cout<<")";
else
cout<<"(";
}
cout<<endl;
for(int j=1; j<=m; j++)
{
if(j>m/2)
cout<<")";
else
cout<<"(";
}
cout<<endl;
for(int j=1; j<=m; j++)
cout<<")";
cout<<endl;
}
else if(m==2)
{
for(int i=1; i<=n; i++)
cout<<"()"<<endl;
}
else if(m==4)
{
for(int i=1; i<=n; i++)
{
if(i<=n/2)
cout<<"()()"<<endl;
else
cout<<"(())"<<endl;
}
}
else
{
for(int j=1; j<=m; j++)
{
cout<<"(";
}
cout<<endl;
for(int i=2; i<=n-1; i++)
{
if(i%2==1)
{
for(int j=1; j<=m; j++)
{
if(j%2==1)
cout<<"(";
else
cout<<")";
}
}
else
{
for(int j=1; j<=m; j++)
{
if(j==1)
cout<<"(";
else if(j==m)
cout<<")";
else
{
if(j%2==0)
cout<<"(";
else
cout<<")";
}
}
}
cout<<endl;
}
for(int j=1; j<=m; j++)
{
cout<<")";
}
cout<<endl;
}
}
}
return 0;
}