hiho Hamiltonian Cycle
来源:互联网 发布:怎样抢到淘宝秒杀产品 编辑:程序博客网 时间:2024/05/22 16:59
#1087 : Hamiltonian Cycle
- 样例输入
4 71 22 33 44 11 34 22 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 31 2
2 1
1 30
这道题让求有向图的哈密顿回路数,数据不大,直接搜。但是正常方法可能会超时,这事就要介绍一种在搜索中可以运用的黑科技:位运算。
由于点不多,所以把每个点所连得边以及已经加入回路中的点用位运算的形式进行表达与传递。减小常数。
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;}
- hiho Hamiltonian Cycle
- Hamiltonian Cycle
- 《Hamiltonian Cycle》题目分析
- hihoCoder 1087 Hamiltonian Cycle
- hihocoder 1087 : Hamiltonian Cycle
- 1122. Hamiltonian Cycle (25)
- 1122. Hamiltonian Cycle (25)
- 1122. Hamiltonian Cycle (25)
- 1122. Hamiltonian Cycle (25)
- 1122. Hamiltonian Cycle (25)
- 1122. Hamiltonian Cycle (25)
- PAT 1122 Hamiltonian Cycle
- 【PAT】1122. Hamiltonian Cycle
- 1122. Hamiltonian Cycle
- 1122. Hamiltonian Cycle (25)
- 1122. Hamiltonian Cycle 解析
- 1122. Hamiltonian Cycle (25)
- 1122. Hamiltonian Cycle (25)
- cocos2dx 基础
- Android修改所有activity的切换动画
- C指针作为函数参数引用
- Android Fragment 基础初识(下)
- Android学习之接口Interface
- hiho Hamiltonian Cycle
- Navicat for MySQL用ssh功能连接远程数据库
- PAT-A1077. Kuchiguse (20)(模拟)
- xib自定义UIView报错误 "forUndefinedKey:]: this class is not key value coding-compliant for the key"
- Android Studio 1.3及以上 NDK环境配置
- 第一次写博客
- HTML+CSS(简单入门)例子
- 快速排序
- PAT-1082. Read Number in Chinese (25)(模拟)