hdu 6400 Parentheses Matrix

题目链接

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
(
()
)(
(((
)))
题意
给一个只含'('和')'的矩阵,只考虑从行和列上的括号序列,构造一个矩阵使得合法括号序列的总数最多
分析
首先奇数行或奇数列内是不存在合法括号序列的,所以如果n或m是奇数,则最多有n/m个括号序列(即把行/列直接填充为合法序列),需要分析的是偶数行和偶数列的情况。
首先贪心一下,起点位于第一行和第一列,所以应该尽量在这些位置填'(',首先想到的是把矩形的左上边界填充为'(',右下边界填充为')'
.((((.
(....)
(....)
(....)
(....)
.)))).

因为第一行,第n行,第1列,第m列一定不是序列,所以这样最多有n+m-4个合法括号序列。

但有一个情况比较特殊,当n=4的时候,上面的方法其实比较亏,以牺牲第一列和最后一列的代价,却只得到了两行合法括号序列。考虑另外一种填充方法:当n比较小的时候,把第一行全部填充为'(',最后一行全部填充为')'
((((((
......
......
))))))

这样以后发现,可以通过调整剩下的位置,让剩下一半的行数成为合法的序列,于是这样最多有(n-2)/2+m=n/2-1+m个合法括号序列
比较一下上面两种方案,假设a>b,当第一种最多a+b-4,第二种最多a+b/2-1,当他们相等时,a+b-4=a+b/2-1,解得b=6,也就是行数列数最小值小于6的时候,应该采用第二种方案能获得更多,而其他情况应该选择第一种情况
总结
一旦某一行是合法序列,那么它一定一半的位置是'(',另一半是')',如果让合法序列出现在首行/列,末行/列,那么一半的列/行都不会是合法序列了,所以这些位置一定不要出现合法序列,那就尽量贪心,尽量填充为全'('或')'。
但是,当行/列数较小的时候,牺牲一半的行/列不一定是坏事,应该特判一下

猜你喜欢

转载自www.cnblogs.com/tobyw/p/9483865.html