状态压缩DP

K - Necklace

Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:327680KB     64bit IO Format:%I64d & %I64u

Description

 

Input

 

Output

 

Sample Input

 

Sample Output

 

Hint

 

Description

  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个珠子,要把他们连成串,每个珠子都要用上,有多少种连法。重点是dp状态转移方程。

代码:

 /*
给出的珠子要全部用上,因此只要最后的状态dp[i][j]中的j能够与第一个珠子相连就行,其中i表示取珠子
的状态,每多加一颗珠子他的dp数就是加上没加之前的dp数(重点!).
*/
#include<iostream>
#include<string>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<queue>
#include<stack>
using namespace std;
int n,m,a,b;
bool d[][];
long long dp[<<][]; //用int过不了
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(dp,,sizeof(dp));
memset(d,,sizeof(d));
for(int i=;i<m;i++)
{
scanf("%d%d",&a,&b);
a--; //这里减一是为了后面写循环简便,也可以不减一
b--;
d[b][a]=;
d[a][b]=;
}
dp[][]=; //初始化第一个当放一个钥匙时总数为1
for(int i=;i<(<<n);i++)
{
for(int j=;j<n;j++)
{
if(dp[i][j]==) continue; //也可以用!(i&(1<<j))来判断,但后者会更费时
for(int k=;k<n;k++) //k也可以从0开始
{
if(!d[k][j]) continue; //判断k与j是否能连接
if(i&(<<k)) continue; //判断第K个钥匙是否已算过
dp[i|(<<k)][k]+=dp[i][j];
}
}
}
long long ans=;
for(int i=;i<n;i++)
{
if(d[][i]) ans+=dp[(<<n)-][i];
}
cout<<ans<<endl;
}
return ;
}
上一篇:mysql学习日记——数据库范式设计


下一篇:高并发简单解决方案————redis队列缓存+mysql 批量入库