O - Necklace

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.
Input
It consists of multi-case . 
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. 
Output
An integer , which means the number of kinds that the necklace could be.
Sample Input
3 3
1 2
1 3
2 3
Sample Output
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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值