时间限制: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
#include "iostream"
#include "string.h"
using namespace std;
int n, m;
int edge[14];
int p[1 << 14];
int cnt = 0;
void dfs(int now, int unUsed)
{
if(!unUsed) //所有的结点都访问过
{
cnt += (edge[now] & 1); //如果回到了结点1,edge[now]最右边是1
return;
}
int rest = unUsed & edge[now]; //既没有访问过,结点now又可达
while(rest) //仍然有后继结点没有访问过
{
int tp = rest & (-rest); //取出最右边的1,即取出一个后继且未访问过的结点
dfs(p[tp], unUsed - tp);
rest -= tp; //从剩余未访问结点中除去
}
}
int main()
{
cin >> n;
cin >> m;
int i;
for(i=0; i<n; i++)
p[1 << i] = i + 1; //p[1000] = 4,是为了方便访问结点
memset(edge, 0, sizeof(edge));
for(i=0; i<m; i++)
{
int u, v;
cin >> u >> v;
edge[u] |= 1 << (v - 1); //edge[u]表示u的后继结点
}
int unUsed = (1 << n) - 2; //因为从结点1开始遍历,所以将最右边的1减去
dfs(1, unUsed);
cout << cnt;
return 0;
}