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
(
()
)(
(((
)))
题意:给出矩形的长宽r,c,要求构造出匹配度最大的括号矩阵。匹配度最大指的是要求整一行或一列能够合理的把括号匹配起来。
((()))合法。()()()合法
思路:根据直播中杜教的指导,遇事不决先打表,然后就可以分析构造了。先粘一下官方题解。
按直播的分析,当h>=6时,如果第一行满足匹配条件了,那么至少有一半括号的列中不能用了,所以要全取(,同理最后一行全取),那么剩下的也就不难看出这种构造了。
代码:
来自:http://www.cnblogs.com/tobyw/p/9483865.html
#include<stdio.h>
char w[202][202];
#define min(a,b) ((a)<(b)?(a):(b))
int main(){
int kase;
int n,m;
scanf("%d",&kase);
while(kase--) {
scanf("%d %d",&n,&m);
if((n&1)&&(m&1)){/*奇数行 奇数列 0个*/
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)w[i][j]='(';
}
else if(n&1){/*奇数行 偶数列 n个*/
for(int i=0;i<n;++i){
w[i][0]='(';
for(int j=1;j<m;++j)
w[i][j]='('+')'-w[i][j-1];
}
}
else if(m&1){/*偶数行 奇数列 m个*/
for(int j=0;j<m;++j){
w[0][j]='(';
for(int i=1;i<n;++i)
w[i][j]='('+')'-w[i-1][j];
}
}
else {/*偶数行 偶数列*/
if(min(n,m)<=6){/*选择方案2*/
if(n>m){//行多,n+m/2-1个
for(int i=0;i<n;++i)w[i][0]='(';
for(int j=1;j<m-1;++j){
w[0][j]='('+')'-w[0][j-1];
for(int i=1;i<n;++i)w[i][j]='('+')'-w[i-1][j];
}
for(int i=0;i<n;++i)w[i][m-1]=')';
}
else {//列多,m+n/2-1个
for(int j=0;j<m;++j)w[0][j]='(';
for(int i=1;i<n-1;++i){
w[i][0]='('+')'-w[i-1][0];
for(int j=1;j<m;++j)w[i][j]='('+')'-w[i][j-1];
}
for(int j=0;j<m;++j)w[n-1][j]=')';
}
}
else {//偶数行,偶数列 列+行-4个
w[0][0]='(';w[0][m-1]=')';
w[n-1][0]='(';w[n-1][m-1]=')';
for(int j=1;j<m-1;++j){//
w[0][j]='(';w[n-1][j]=')';
}
for(int i=1;i<n-1;++i){
w[i][0]='(';w[i][m-1]=')';
}
for(int i=1;i<n-1;++i){
w[i][1]='('+')'-w[i-1][1];
for(int j=2;j<m-1;++j){
w[i][j]='('+')'-w[i][j-1];
}
}
}
}
/*输出*/
for(int i=0;i<n;++i){
for(int j=0;j<m;++j)
printf("%c",w[i][j]);
printf("\n");
}
}
}