題目鏈接:點擊查看
題目大意:給出一個 n * m 大小的空矩陣,要求在某些位置放置 1 ,其餘位置放置 0 ,使得每行都有恰好 a 個 1 ,且每列恰好有 b 個 1 ,給出一種構造方案或者判斷是否可行
題目分析:棋盤問題,加上數據比較小,考慮直接用網絡流直接判斷是否可行,行列約束可以轉換爲流量約束,具體建圖方式如下:
- 源點 -> 每一行,流量爲 a
- 每一行 -> 每一列,流量爲 1
- 每一列 -> 匯點,流量爲 b
建完圖後不難看出,當且僅當 a * n == b * m 才存在滿流的情況,所以可以提前判斷 NO 的情況,然後用最大流跑出一種可行方案輸出即可
代碼:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<unordered_map>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=110;
struct Edge
{
int to,w,next;
}edge[N*N];
int head[N],cnt;
void addedge(int u,int v,int w)
{
edge[cnt].to=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
edge[cnt].to=u;
edge[cnt].w=0;
edge[cnt].next=head[v];
head[v]=cnt++;
}
int d[N],now[N];
bool bfs(int s,int t)
{
memset(d,0,sizeof(d));
queue<int>q;
q.push(s);
now[s]=head[s];
d[s]=1;
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
int w=edge[i].w;
if(d[v])
continue;
if(!w)
continue;
d[v]=d[u]+1;
now[v]=head[v];
q.push(v);
if(v==t)
return true;
}
}
return false;
}
int dinic(int x,int t,int flow)
{
if(x==t)
return flow;
int rest=flow,i;
for(i=now[x];i!=-1&&rest;i=edge[i].next)
{
int v=edge[i].to;
int w=edge[i].w;
if(w&&d[v]==d[x]+1)
{
int k=dinic(v,t,min(rest,w));
if(!k)
d[v]=0;
edge[i].w-=k;
edge[i^1].w+=k;
rest-=k;
}
}
now[x]=i;
return flow-rest;
}
void init()
{
memset(now,0,sizeof(now));
memset(head,-1,sizeof(head));
cnt=0;
}
int solve(int st,int ed)
{
int ans=0,flow;
while(bfs(st,ed))
while(flow=dinic(st,ed,inf))
ans+=flow;
return ans;
}
bool maze[55][55];
int main()
{
#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);
int w;
cin>>w;
while(w--)
{
init();
int n,m,a,b;
scanf("%d%d%d%d",&n,&m,&a,&b);
if(n*a!=m*b)
{
puts("NO");
continue;
}
puts("YES");
int st=N-1,ed=st-1;
for(int i=1;i<=n;i++)
addedge(st,i,a);
for(int i=1;i<=m;i++)
addedge(i+n,ed,b);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
addedge(i,j+n,1);
solve(st,ed);
memset(maze,false,sizeof(maze));
for(int i=1;i<=n;i++)
for(int j=head[i];j!=-1;j=edge[j].next)
if(edge[j].w==0&&edge[j].to>n&&edge[j].to<=m+n)
maze[i][edge[j].to-n]=true;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
printf("%d",maze[i][j]);
puts("");
}
}
return 0;
}