#1087 : Hamiltonian Cycle
-
4 7 1 2 2 3 3 4 4 1 1 3 4 2 2 1
样例输出
-
2
描述
Given a directed graph containing n vertice (numbered from 1 to n) and m edges. Can you tell us how many different Hamiltonian Cycles are there in this graph?
A Hamiltonian Cycle is a cycle that starts from some vertex, visits each vertex (except for the start vertex) exactly once, and finally ends at the start vertex.
Two Hamiltonian Cycles C1, C2 are different if and only if there exists some vertex i that, the next vertex of vertex i in C1 is different from the next vertex of vertex i in C2.
输入
The first line contains two integers n and m. 2 <= n <= 12, 1 <= m <= 200.
Then follows m line. Each line contains two different integers a and b, indicating there is an directed edge from vertex a to vertex b.
输出
Output an integer in a single line -- the number of different Hamiltonian Cycles in this graph.
提示
额外的样例:
样例输入 | 样例输出 |
3 3 1 2 2 1 1 3 | 0 |
这道题让求有向图的哈密顿回路数,数据不大,直接搜。但是正常方法可能会超时,这事就要介绍一种在搜索中可以运用的黑科技:位运算。
由于点不多,所以把每个点所连得边以及已经加入回路中的点用位运算的形式进行表达与传递。减小常数。
rest&(-rest):可以得到最靠右的二次幂的数。比如rest=5(101)时,5&(-5)=1;rest=4(100)时,4&(-4)=4(100)。真是66666
#include<cstdio>
#include<cstring>
using namespace std;
int edge[14],p[1<<12],n,m,ans;
void dfs(int u,int sta){
if(!sta){
ans+=(edge[u]&1);return;
}
int rest=sta&edge[u],tp;
while(rest){
tp=rest&(-rest);
dfs(p[tp],sta^tp);
rest-=tp;
}
}
int main(){
int u,v;
for(int i=0;i<12;++i) p[1<<i]=i+1;
while(~scanf("%d%d",&n,&m)){
memset(edge,0,sizeof(edge));
for(int i=0;i<m;++i){
scanf("%d%d",&u,&v);
edge[u]|=(1<<(v-1));
}
ans=0;dfs(1,(1<<n)-2);
printf("%d\n",ans);
}
return 0;
}