An n × n square matrix is special, if:
- it is binary, that is, each cell contains either a 0, or a 1;
- the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n × n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
The first line of the input contains three integers n, m, mod (2 ≤ n ≤ 500, 0 ≤ m ≤ n, 2 ≤ mod ≤ 109). Then m lines follow, each of them contains n characters — the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m × n table contains at most two numbers one.
Print the remainder after dividing the required value by number mod.
3 1 1000 011
2
4 4 100500 0110 1010 0101 1001
1
For the first test the required matrices are:
011 101 110 011 110 101
In the second test the required matrix is already fully given, so the answer is 1.
F题O(n^2)解法。
设dp[i][j]表示已经有i列上有两个1,j列上有1个1,剩下的n-i-j列上还没有1。
那么,由于i的不递减,所以我们可以将这个作为递推的第一维。
dp[i][j + 2] += ( n - i - j ) * ( n - i - j - 1 ) / 2 * dp[i][j].(选择没有1的两列将其变成有一个1的两列)
dp[i + 1][j] += j * ( n - i - j ) * dp[i][j].(j>0)(选择一列有一个1的变成有两个1的,同时选择没有1的变成有一个1的)
dp[i + 2][j - 2] += j * ( j - 1 ) / 2 * dp[i][j].(j>1)(选择有一个1的两列变成有两个1的两列)
这样推法的可行性在于充分利用1的数量是固定的隐性条件,到最后终点dp[n][0]时的一定是合法的。
#include <iostream>
#include <cstdio>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include<ctime>
#define esp 1e-6
#define LL long long
#define inf 0x0f0f0f0f
using namespace std;
LL dp[505][505];
int num[505][505],a[505];
int main()
{
int n,m,mod;
int i,j;
char ss[1005];
while(scanf("%d%d%d",&n,&m,&mod)!=EOF)
{
memset(dp,0,sizeof(dp));
memset(a,0,sizeof(a));
memset(num,0,sizeof(num));
getchar();
for(i=1;i<=m;i++)
{
gets(ss);
for(j=0;j<n;j++)
num[i][j+1]=ss[j]-'0';
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(num[j][i]!=0)
a[i]++;
}
}
int x,y;
x=0;
y=0;
for(i=1;i<=n;i++)
{
if(a[i]==2)
x++;
if(a[i]==1)
y++;
}
dp[x][y]=1;
for(i=x;i<=n;i++)
for(j=0;j<=n-i;j++)
if(dp[i][j])
{
dp[i][j+2]+=(n-i-j)*(n-i-j-1)/2*dp[i][j]%mod;
dp[i+1][j]+=j*(n-i-j)*dp[i][j]%mod;
if(j>=2)
dp[i+2][j-2]+=j*(j-1)/2*dp[i][j]%mod;
}
printf("%I64d\n",dp[n][0]);
}
}