状态DP求哈密顿回路个数 CodeForces 11D——A Simple Task

来源:互联网 发布:mac os 10.12 beta6 编辑:程序博客网 时间:2024/05/22 03:45

题意:求一个图中(节点个数小于20)长度大于等于三的哈密顿路径数目

题解:

由于节点数不多,可用状态压缩DP

dp[set][i]:由set节点组成的子图中以节点i为尾的简单路径的数目

为防止重复计数,我们假设路径的起点都是set中标号最小的节点。

如:set=6(二进制表示为:0110)表示包含1、2号节点的子图,其中1号节点是最小节点


代码如下:

#include<cstdio>#include<cstring>#define N 20#define ll long longint map[N][N],n,m,u,v;ll dp[1<<N][N];int first(int x){    for(int i=0;i<n;i++) if(x&(1<<i)) return i;}int cnt(int x){    int ans=0;    for(int i=0;i<n;i++) if(x&(1<<i)) ans++;    return ans;}int main(){    //freopen("4.in","r",stdin);    while(scanf("%d%d",&n,&m)!=EOF) {        memset(map,0,sizeof(map));        memset(dp,0,sizeof(dp));        for(int i=0;i<m;i++) {            scanf("%d%d",&u,&v);            u--,v--;            map[u][v]=map[v][u]=1;        }        ll ans=0;        for(int i=0;i<N;i++) dp[1<<i][i]=1;        for(int st=1;st<(1<<n);st++) {            int s=first(st);            for(int e=s;e<n;e++) {                if(st&(1<<e)) {                    for(int i=s;i<n;i++) {                        int nst=st|(1<<i);                        if(map[e][i] && (st&(1<<i))==0) {                            dp[nst][i]+=dp[st][e];                            if(map[i][s] && cnt(nst)>2) ans+=dp[st][e];//如果可首尾相连且长度大于3则计数                        }                    }                }            }        }        printf("%I64d\n",ans/2);    }    return 0;}


题目如下:

题目链接:here

A Simple Task
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges.

Input

The first line of input contains two integers n and m (1 ≤ n ≤ 190 ≤ m) – respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1 ≤ a, b ≤ na ≠ b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices.

Output

Output the number of cycles in the given graph.

Sample test(s)
input
4 61 21 31 42 32 43 4
output
7
Note

The example graph is a clique and contains four cycles of length 3 and three cycles of length 4.



原创粉丝点击