hiho Hamiltonian Cycle

#1087 : Hamiltonian Cycle

时间限制: 10000ms
单点时限: 1000ms
内存限制: 256MB

描述

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




样例输入
4 7
1 2
2 3
3 4
4 1
1 3
4 2
2 1
样例输出

2

这道题让求有向图的哈密顿回路数,数据不大,直接搜。但是正常方法可能会超时,这事就要介绍一种在搜索中可以运用的黑科技:位运算。

由于点不多,所以把每个点所连得边以及已经加入回路中的点用位运算的形式进行表达与传递。减小常数。

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值