Necklace HDU - 3091
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[s][j]表示状态s时j为最后一个珠子有多少个 d p [ s ] [ j ] 表 示 状 态 s 时 j 为 最 后 一 个 珠 子 有 多 少 个
状态转移的时候就枚举1-n个珠子i,如果这个珠子i还没用,并且和j即前一个状态下的末尾珠子相连,就可以更新,状态转移到新的状态,即现在成了以i结尾的了
最后在累加的过程中,以i为结尾的是否能和1相连,如果可以那么就构成了了满足题意的哈密尔顿回路,就加上
code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1 << 20;
ll dp[maxn][20];//dp[s][j]表示状态s下以j为结尾的个数
int dis[20][20];
int main(){
int n,m;
while(scanf("%d%d",&n,&m) != EOF){
memset(dis,0,sizeof(dis));
while(m--){
int a,b;
scanf("%d%d",&a,&b);
dis[a][b] = dis[b][a] = 1;//相当于存图,代表ab间有连边
}
memset(dp,0,sizeof(dp));
dp[1][1] = 1;
for(int s = 1; s < (1 << n); s++){
for(int j = 1; j <= n; j++){//枚举要更新的dp,更新s状态下j结尾的dp的值
if(!dp[s][j]) continue;//如果为0,说明这种状态不存在
for(int i = 1; i <= n; i++){//在结尾加上新的石头i,即现在要以i为结尾
if(s & (1 << (i-1))) continue;//如果这个石头在原状态已经有了,跳过
if(!dis[i][j]) continue;//如果ij不相连,跳过
dp[s|(1 << (i-1))][i] += dp[s][j];
}
}
}
ll ans = 0;
int S = (1 << n) - 1;
for(int i = 1; i <= n; i++){
if(dis[i][1]){//说明首尾能够相连
ans += dp[S][i];
}
}
printf("%lld\n",ans);
}
return 0;
}