Necklace (状态dp)

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个珠子,接下来会有m行,表示哪两个珠子可以互相连接。问有多少种连接方案。

思路:

状态dp。

可以把所有珠子压缩成一个数。

dp【i】【j】表示到了状态i,第j个珠子的时候,方案数量。

状态转移方程dp[i|tem][k]+=dp[i][j];


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int ma=20;
long long dp[1<<ma][ma];
int v[ma][ma];
int n,m;
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        memset(v,0,sizeof(v));

        for(int i=1;i<=m;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            v[a-1][b-1]=v[b-1][a-1]=1;
        }
        memset(dp,0,sizeof(dp));
        int cnt=1<<n;
        dp[1][0]=1;
        for(int i=1;i<cnt;i++)//枚举所有状态
        {
            for(int j=0;j<n;j++)//枚举所有珠子
            {
                if(dp[i][j]!=0&&(i&(1<<j)))//判断条件
                {
                    for(int k=1;k<n;k++)//枚举哪个珠子在本珠子后面。
                    {
                        int tem=(1<<k);
                        if(!(i&tem)&&v[j][k])//判断条件
                        {
                            dp[i|tem][k]+=dp[i][j];
                        }
                    }
                }
            }
        }

        long long sum=0;
        for(int i=0;i<n;i++)
        {
            if(v[0][i])
            {
                sum+=dp[cnt-1][i];
            }
        }
        printf("%I64d\n",sum);
    }

    return 0;
}





评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值