本文主要是介绍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
(
()
)(
(((
)))
最讨厌这种题目了,又想不到,代码又长,都是if和else,而且在比赛的时候还没做出来QAQ
特判双偶数的情况n==2和n==4的情况,其他情况就是牺牲4边来构成最大平衡
代码很丑= =,将就着看。
#include<bits/stdc++.h>
using namespace std;
char Map[205][205];
int main()
{int t;scanf("%d",&t);while(t--){int n,m;scanf("%d%d",&n,&m);if(n%2&&m%2){for(int i=1;i<=n;i++){for(int j=1;j<=m;j++)printf("(");printf("\n");}}else if(n%2){for(int i=1;i<=n;i++){for(int j=1;j<=m;j+=2)printf("()");printf("\n");}}else if(m%2){for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){if(i%2)printf("(");elseprintf(")");}printf("\n");}}else{int flag=0;if(n>m)swap(n,m),flag=1;if(n==2){for(int i=1;i<=n;i++){for(int j=1;j<=m;j++)Map[i][j]=(i==1?'(':')');}}else if(n==4){for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){if(i==1)Map[i][j]='(';else if(i==2){if(j<=m/2)Map[i][j]=')';elseMap[i][j]='(';}else if(i==3){if(j<=m/2)Map[i][j]='(';elseMap[i][j]=')';}else{Map[i][j]=')';}}}}else{for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){if(i==1)Map[i][j]='(';else if(i==n)Map[i][j]=')';else if(i%2==0){if(j%2)Map[i][j]='(';elseMap[i][j]=')';}else{if(j==1)Map[i][j]='(';else if(j==m)Map[i][j]=')';else if(j%2==0)Map[i][j]='(';elseMap[i][j]=')';}}}}if(flag){for(int j=1;j<=m;j++){for(int i=1;i<=n;i++)printf("%c",Map[i][j]);printf("\n");}}else{for(int i=1;i<=n;i++){for(int j=1;j<=m;j++)printf("%c",Map[i][j]);printf("\n");}}}}return 0;
}
这篇关于Parentheses Matrix —— 枚举+模拟的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!