One day , Partychen gets several beads , he wants to make these beads a necklace . But not every beads can link to each other, every bead should link to some particular bead(s). Now , Partychen wants to know how many kinds of necklace he can make.
Every case start with two integers N,M ( 1<=N<=18,M<=N*N )
The followed M lines contains two integers a,b ( 1<=a,b<=N ) which means the ath bead and the bth bead are able to be linked.
3 3 1 2 1 3 2 3
2
N个珠子连成一串,按照给的要求,相应的珠子能相连,求多少种可能。
对于每个珠子,首先我们知道只有放完了和没有放(0/1)两种可能,把N个珠子一起组成的二进制数压缩,形成MM个状态,再分别讨论就好。这里用dp[i][j]表示状态i,最后放的是第j种珠子的种类数,对于MM个状态,每个状态都探讨一下以放完的珠子和要放的珠子,将方案数累加。要注意要先选定1号珠子为第一个珠子,最后第N个珠子选择能和第一个相连的珠子,求和即可。
代码如下:
#include<iostream>
#include<cstring>
typedef long long LL;
using namespace std;
const int MAX=1<<20;
LL dp[MAX][20];//状态i,最后放的是j种珠子
int mp[20][20];
int main()
{
int N, M, MM;
int u, v;
while(cin>>N>>M)
{
memset(mp, 0, sizeof(mp));
for(int i=1; i<=M; i++)
{
cin>>u>>v;
mp[u][v]=mp[v][u]=1;
}
MM=1<<N;//MM种状态,相应的二进制代表该种珠子有没有放过
memset(dp, 0, sizeof(dp));
dp[1][1]=1;//以第1个珠子开始
for(int i=1; i<MM; i++)//状态i
{
for(int j=1; j<=N; j++)//枚举所有已放的珠子
{
if(dp[i][j]==0)//没放过的跳过
continue;
for(int k=2; k<=N; k++)//下次要放的珠子
{
if(i & (1<<(k-1)))//放过的跳过
continue;
if(!mp[j][k])//不能连的跳过
continue;
dp[i|(1<<(k-1))][k]+=dp[i][j];//状态i变,种类数加
}
}
}
LL sum=0;
for(int i=1; i<=N; i++)
{
if(mp[1][i])//对能和开始1相连的求和
sum+=dp[MM-1][i];
}
cout<<sum<<endl;
}
return 0;
}