您的位置:首页 > 其它

Special Matrices - CodeForces 489 F dp

2014-11-18 18:03 381 查看
F. Special Matrices

time limit per test
1 second

memory limit per test
256 megabytes

input
standard input

output
standard output

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.

Input

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.

Output

Print the remainder after dividing the required value by number mod.

Sample test(s)

input
3 1 1000
011


output
2


input
4 4 100500
0110
1010
0101
1001


output
1


Note

For the first test the required matrices are:
011101110

011110
101


In the second test the required matrix is already fully given, so the answer is 1.

题意:构建一个n*n的矩阵使得每行每列各有两个1,且前m行已给出,问有多少种可能的情况。

思路:dp[s1][s2]表示轮到该行的时候有s1个列可以放2个1,s2个列可以放1个1,然后转移的话很简单,代码页不长。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
ll dp[510][510],num[510],MOD;
char s[510];
int main()
{
    int n,m,i,j,k,a=0,b=0,len,s1=0,s2=0;
    scanf("%d%d%I64d",&n,&m,&MOD);
    for(i=1;i<=m;i++)
    {
        scanf("%s",s+1);
        for(j=1;j<=n;j++)
           if(s[j]=='1')
             num[j]++;
    }
    for(i=1;i<=n;i++)
       if(num[i]==0)
         s1++;
       else if(num[i]==1)
         s2++;

    len=n-m;
    dp[s1][s2]=1;
    for(i=m+1;i<=n;i++)
    {
           for(s1=0;s1<=n;s1++)
           {
               s2=(n-i+1)*2-s1*2;
               if(s2<0 || s2>n)
                continue;
               if(s1>=2)
                 dp[s1-2][s2+2]=(dp[s1-2][s2+2]+dp[s1][s2]*s1*(s1-1)/2)%MOD;
               if(s1>=1)
               dp[s1-1][s2]=(dp[s1-1][s2]+dp[s1][s2]*s1*s2)%MOD;
               if(s2>=2)
                 dp[s1][s2-2]=(dp[s1][s2-2]+dp[s1][s2]*s2*(s2-1)/2)%MOD;
           }
    }
    printf("%I64d\n",dp[0][0]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: