CF11D:A Simple Task(状压dp & 图)

本文介绍了一种高效算法,用于计算给定简单图中的简单环数量。通过使用位操作和动态规划技巧,该算法能在有限时间内找出所有不重复顶点和边的环。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

D. A Simple Task
time limit per test
2 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.

Examples
input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
output
7
Note

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

题意:给N个点,M条边,计算有几个简单环。

思路:转成计算有几条链能成环,限定链上最小的数字为起点,dp[i][j]为i状态下,以j为终点的链有几条,最后答案除二即可。

# include <bits/stdc++.h>
using namespace std;
int v[20][20]={0};
long long dp[1<<20][20]={0};
int main()
{
    int n, m, st=0;
    long long ans=0;
    scanf("%d%d",&n,&m);
    while(m--)
    {
        int a, b;
        scanf("%d%d",&a,&b);
        --a;--b;
        v[a][b] = v[b][a] = 1;
    }
    for(int i=0; i<n; ++i) dp[1<<i][i] = 1;
    for(int i=1; i<1<<n; ++i)
    {
        for(int j=0; j<n; ++j)
        {
            if(dp[i][j] == 0) continue;
            for(int k=0; k<n; ++k)
            {
                if(i&(1<<k))
                {
                    st = k;
                    break;
                }
            }
            if(v[j][st] && __builtin_popcount(i)>2) ans += dp[i][j];
            for(int k=st+1; k<n; ++k)
                if(!(i&(1<<k)) && v[j][k]) dp[i|(1<<k)][k] += dp[i][j];
        }
    }
    printf("%lld\n",ans/2);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值