1004: [HNOI2008]Cards
Time Limit: 10 Sec Memory Limit: 162 MB
Submit: 1025 Solved: 590
[Submit][Status][Discuss]
Description
小春现在很清闲,面对书桌上的N张牌,他决定给每张染色,目前小春只有3种颜色:红色,蓝色,绿色.他询问Sun有多少种染色方案,Sun很快就给出了答案.进一步,小春要求染出Sr张红色,Sb张蓝色,Sg张绝色.他又询问有多少种方案,Sun想了一下,又给出了正确答案. 最后小春发明了M种不同的洗牌法,这里他又问Sun有多少种不同的染色方案.两种染色方法相同当且仅当其中一种可以通过任意的洗牌法(即可以使用多种洗牌法,而每种方法可以使用多次)洗成另一种.Sun发现这个问题有点难度,决定交给你,答案可能很大,只要求出答案除以P的余数(P为质数).
Input
第一行输入 5 个整数:Sr,Sb,Sg,m,p(m<=60,m+1<p<100)。n=Sr+Sb+Sg。接下来 m 行,每行描述
一种洗牌法,每行有 n 个用空格隔开的整数 X1X2...Xn,恰为 1 到 n 的一个排列,表示使用这种洗牌法,
第 i位变为原来的 Xi位的牌。输入数据保证任意多次洗牌都可用这 m种洗牌法中的一种代替,且对每种
洗牌法,都存在一种洗牌法使得能回到原状态。
100%数据满足 Max{Sr,Sb,Sg}<=20。
Output
不同染法除以P的余数
Sample Input
1 1 1 2 7
2 3 1
3 1 2
Sample Output
2
HINT
有2 种本质上不同的染色法RGB 和RBG,使用洗牌法231 一次可得GBR 和BGR,使用洗牌法312 一次 可得BRG 和GRB。
解析:
这道题思想难度有点大,这推荐几篇blog
http://blog.csdn.net/cjoilmd/article/details/7400705
http://hi.baidu.com/jiangzoi/item/0cf3e1ce5393bf6af7c95d3e
我也是仿照大神的代码写的。。。
代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 70
bool step[N];
int id[N],dp[N][N][N],g[N],st[N],sum[N];
void read()
{
freopen("cards.in","r",stdin);
freopen("cards.out","w",stdout);
}
int sr,sb,sg,n,m,p;
int dfs(int u)
{
step[u]=true;
if(step[g[u]])return 1;
return dfs(g[u])+1;
}
int quick(int a,int b)
{
int c=1;
while(b)
{
if(b&1)c=c*a%p;
b>>=1;
a=a*a%p;
}
return c;
}
int main()
{
read(); int cnt;
scanf("%d%d%d%d%d",&sr,&sb,&sg,&m,&p);
int n=sr+sb+sg;m++; int q,ans=0;
for(int i=1;i<=m;i++)
{
cnt=0;
if(i==m)for(int j=1;j<=n;j++)g[j]=j;
else for(int j=1;j<=n;j++)scanf("%d",&g[j]);
memset(step,0,sizeof(step));
memset(dp,0,sizeof(dp));
memset(id,0,sizeof(id));
for(int j=1;j<=n;j++)
if(!step[j])st[++cnt]=dfs(j);
for(int j=1;j<=cnt;j++)sum[j]=sum[j-1]+st[j],id[sum[j]]=j;
dp[0][0][0]=1;
for(int j=0;j<=sr;j++)
for(int k=0;k<=sb;k++)
for(int z=0;z<=sg;z++)
if(q=id[j+k+z])
{
if(j>=st[q])dp[j][k][z]+=dp[j-st[q]][k][z]%=p;
if(k>=st[q])dp[j][k][z]+=dp[j][k-st[q]][z]%=p;
if(z>=st[q])dp[j][k][z]+=dp[j][k][z-st[q]]%=p;
}
ans=(ans+dp[sr][sb][sg])%p;
}
ans=ans*quick(m,p-2)%p;
printf("%d\n",ans);
return 0;
}