Solution
考虑从大到小填数。
定义一行或一列被覆盖当且仅当这一行或列已经填了至少一个数,这就意味着之后随便填都不会影响最大值。
设
N
、
M
N、M
N、M分别为当前覆盖的行和列数。
对于每个填的数,分几种情况讨论:
1、有一行和一列以它为最大值,此时填的位置固定。
2、有一行或一列以它为最大值,此时它只能填在那一行或一列一个被覆盖的位置上,
a
n
s
ans
ans乘上
N
N
N或
M
M
M。
3、没有行和列以它为最大值,此时它只能填在一个行列都被覆盖的位置上,即一个交点上,
a
n
s
ans
ans乘上
N
×
M
−
c
n
t
N\times M-cnt
N×M−cnt(
c
n
t
cnt
cnt为当前填了多少数)。
Code
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pa pair<int,int>
const int Maxn=1010;
const int inf=2147483647;
const int mod=1000000007;
int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
return x*f;
}
int n,m,a[Maxn],b[Maxn],cx[Maxn*Maxn],cy[Maxn*Maxn],px[Maxn*Maxn],py[Maxn*Maxn];
int main()
{
memset(px,-1,sizeof(px));
memset(py,-1,sizeof(py));
n=read(),m=read();
for(int i=1;i<=n;i++)cx[a[i]=read()]++,px[a[i]]=i;
for(int i=1;i<=m;i++)cy[b[i]=read()]++,py[b[i]]=i;
for(int i=1;i<=n*m;i++)if(cx[i]>2||cy[i]>2)return puts("0"),0;
int N=0,M=0,ans=1,cnt=0;
for(int i=n;i;i--)
for(int j=m;j;j--)
{
int x=(i-1)*m+j;
if(px[x]!=-1&&py[x]!=-1)N++,M++,cnt++;
else if(px[x]!=-1)
{
if(!M)return puts("0"),0;
N++,cnt++;
ans=(LL)ans*M%mod;
}
else if(py[x]!=-1)
{
if(!N)return puts("0"),0;
M++,cnt++;
ans=(LL)ans*N%mod;
}
else
{
if(N*M-cnt==0)return puts("0"),0;
ans=(LL)ans*(N*M-cnt)%mod;cnt++;
}
if(N>n||M>m)return puts("0"),0;
}
printf("%d",ans);
}