HDU 6122 Color the chessboard(机智)

来源:互联网 发布:网上药店软件 编辑:程序博客网 时间:2024/04/30 06:59

Description

一个nm的棋盘,上面有三种棋子B,R??可以变成BR,问有多少中合法的赋值方案使得任意一个偶行偶列的子矩阵中B的数量和R的数量相同

Input

第一行一整数T表示用例组数,每组用例首先输入两个整数nm表示棋盘行列数,之后输入一个nm的字符矩阵表示该棋盘(1T5,1n,m103)

Output

输出方案数,结果模998244353

Sample Input

2
2 2
RB
??
3 3
???
?R?
???

Sample Output

2
7

Solution

问题转化为对于任意一个22的子矩阵有两个B和两个R,共6种情况,注意到如果把所有奇格中的棋子反色,把B看作1把R看作0,那么每个22的矩阵的主对角线之和等于反对角线之和,而满足该条件的矩阵只有两种:每行都相同或每列都相同(固定左上角的22矩阵后递推可得),故求出这两种情况的方案数加起来之后再减去整个矩阵都相同的方案即为答案

Code

#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>#include<cmath>#include<vector>#include<queue>#include<map>#include<set>#include<ctime>using namespace std;typedef long long ll;#define maxn 1005#define mod 998244353int T,n,m,row[maxn],col[maxn],nr,nc,flag;char s[maxn];void inc(int &a,int b){    a=a+b>=mod?a+b-mod:a+b;} void dec(int &a,int b){    a=a-b<0?a-b+mod:a-b;}int mod_pow(int a,int b){    int ans=1;    while(b)    {        if(b&1)ans=(ll)ans*a%mod;        a=(ll)a*a%mod;        b>>=1;    }    return ans;}int main(){    scanf("%d",&T);    while(T--)    {        scanf("%d%d",&n,&m);        nr=n,nc=m,flag=0;        for(int i=1;i<=n;i++)row[i]=0;        for(int i=1;i<=m;i++)col[i]=0;        for(int i=1;i<=n;i++)        {            scanf("%s",s+1);            for(int j=1;j<=m;j++)                if(s[j]!='?'&&!(nr==-1&&nc==-1))                {                    int type;                    if(s[j]=='R')type=1;                    else type=2;                    if((i+j)&1)type=3-type;                    if(row[i]==3-type)nr=-1;                    else if(!row[i])nr--,row[i]=type;                    if(col[j]==3-type)nc=-1;                    else if(!col[j])nc--,col[j]=type;                    if(flag!=-1)                        if(flag==3-type)flag=-1;                        else flag=type;                }        }        int ans=0;        if(nr>=0)inc(ans,mod_pow(2,nr));        if(nc>=0)inc(ans,mod_pow(2,nc));        if(flag!=-1)        {            if(flag==0)dec(ans,2);            else dec(ans,1);        }        printf("%I64d\n",ans);    }    return 0;}
原创粉丝点击