You are given four positive integers n, m, a, b (1≤b≤n≤50; 1≤a≤m≤50). Find any such rectangular matrix of size n×m that satisfies all of the following conditions:
each row of the matrix contains exactly a ones;each column of the matrix contains exactly b ones;all other elements are zeros.If the desired matrix does not exist, indicate this.
For example, for n=3, m=6, a=2, b=1, there exists a matrix satisfying the conditions above:
|010001100100001010|
Input
The first line contains an integer t (1≤t≤1000) — the number of test cases. Then t test cases follow.
Each test case is described by four positive integers n, m, a, b (1≤b≤n≤50; 1≤a≤m≤50), where n and m are the sizes of the matrix, and a and b are the number of ones for rows and columns, respectively.
Output
For each test case print:
"YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or"NO" (without quotes) if it does not exist.To print the matrix n×m, print n rows, each of which consists of m numbers 0 or 1 describing a row of the matrix. Numbers must be printed without spaces.
Example
Input
5 3 6 2 1 2 2 2 1 2 2 2 2 4 4 2 2 2 1 1 2Output
YES 010001 100100 001010 NO YES 11 11 YES 1100 1100 0011 0011 YES 1 1题意:多组输入,每组输入n,m,a,b,要求输出YES和一个n*m的数组,其中每行有a个1,每列有b个1,其余为0.若没有符合条件的数组,输出NO。
贴一个我自己的wrong的代码,暂时还没完全弄明白。
#include<iostream> #include<algorithm> using namespace std; int t, n, m, a, b; int main(){ scanf("%d", &t); while(t--){ scanf("%d%d%d%d", &n, &m, &a, &b); if(n*a != m*b){ printf("NO\n");continue;} int line[51], list[51];//行、列 for(int i=0; i<n; i++) line[i] = a; for(int i=0; i<m; i++) list[i] = b; printf("YSE\n"); for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(line[i] && list[j]){ printf("1"); line[i]--;list[j]--; }else printf("0"); } printf("\n"); } } }吸收各方大佬以后按照他们的方法写的ac的代码
#include<iostream> using namespace std; int s[52][52]; int t, n, m, a, b; int main(){ scanf("%d", &t); while(t--){ scanf("%d%d%d%d", &n, &m, &a, &b); if(n*a != m*b){ printf("NO\n");continue;} for(int i=0; i<n; i++) for(int j=0; j<m; j++) s[i][j] = 0; for(int i=0, j=0; i<n; i++, j=(j+a)%m) for(int k=0; k<a; k++) s[i][(j+k)%m] = 1; printf("YES\n"); for(int i=0; i<n; i++){ for(int j=0; j<m; j++) printf("%d", s[i][j]); printf("\n"); } } return 0; }