Codeforces 1360G - A/B Matrix (思维/贪心)


题面

Time limit per test: 2 seconds

Memory limit per test: 256 megabytes

Description

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:

Probpic1

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 2

output

YES
010001
100100
001010
NO
YES
11
11
YES
1100
1100
0011
0011
YES
1
1



题意

要求找出一个 n*m 的矩阵

要求每一行严格存在 a 个 '1'

每一列严格存在 b 个 '1'

其余部分均为 '0'




解题思路

换言之也就是要填充 n*a 或 b*m 个 '1'

所以只要 n*a == b*m 成立,则一定存在答案

既然保证存在答案,那么就可以按照阶梯状填充字符 '1'

将式子移项得 n*a/m == b

即我们填充 n 行,每行 a 个 '1' 时,总共填充的个数一定是 m 的倍数

若将 n*m 矩阵变成一个 1*m 的,让 '1' 在这个单行矩阵中填充,每个位置填充 b 次

那么肯定是从第一个位置开始,每次向后填充 a 个,循环填充一整行才是最优解

即每一行的 '1' 都连续,且下一行第一个 '1' 紧跟在上一行最后一个 '1' 之后


例:

①在 3*6 的矩阵中

a=2 b=1

则构造出了矩阵

110000

001100

000011

②在 2*6 的矩阵中

a=3 b=1

则构造出了矩阵

111000

000111

③在 6*6 的矩阵中

a=2 b=2

则构造出了矩阵

110000

001100

000011

110000

001100

000011

④在 6*6 的矩阵中

a=4 b=2

则构造出了矩阵

111100

110011

001111


从上述例子中可以观察到 '1' 的位置规律




完整代码

#include<bits/stdc++.h>
using namespace std;

char mp[55][55];

void solve()
{
    int n,m,a,b,p=0;
    cin>>n>>m>>a>>b;
    
    if(n*a!=b*m) //不存在解
    {
        cout<<"NO\n";
        return;
    }
    
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
            mp[i][j]='0';
    
    for(int i=0;i<n;i++)
        for(int j=0;j<a;j++) //以p为起始位置,每次向后填充a个'1'
        {
            mp[i][p]='1';
            p=(p+1)%m; //循环
        }
    
    cout<<"YES\n";
    for(int i=0;i<n;i++)
    {
        mp[i][m]='\0';
        cout<<mp[i]<<'\n';
    }
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int T;cin>>T;
    while(T--)
        solve();
    return 0;
}

posted @ 2020-05-25 09:56  StelaYuri  阅读(464)  评论(0编辑  收藏  举报