CodeForces 11D(状压DP 求图中环的个数)
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?≤?19,?0?≤?m) – respectively the number of vertices and edges of the graph. Each of the subsequent?mlines contains two integers?a?and?b, (1?≤?a,?b?≤?n,?a?≠?b) indicating that vertices?aand?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.
Example
Input 4 61 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.
?1-2-3 2-3-4 1-3-4 1-2-4 1-2-3-4 1-2-4-3 1-4-2-3
題意:給出一個(gè)圖的點(diǎn)數(shù)和邊數(shù)輸出這個(gè)圖中有幾個(gè)環(huán).
題解:這道題可以很容易想到狀壓,因?yàn)閿?shù)據(jù)也只有19(orz).用sta的二進(jìn)制表示已經(jīng)有幾個(gè)點(diǎn)在這個(gè)狀態(tài)中,那怎么表示形成環(huán)呢?只需要找到一個(gè)當(dāng)前狀態(tài)中的點(diǎn),它神奇的與前面的某一個(gè)點(diǎn)有一條邊連著,那么說明肯定能構(gòu)成環(huán),可以為總答案做貢獻(xiàn).如果不能,那么就為下一個(gè)狀態(tài)提供個(gè)數(shù).不過由于是無向圖.所以兩個(gè)點(diǎn)也會(huì)被認(rèn)為成環(huán)(兩個(gè)點(diǎn)構(gòu)成環(huán)的個(gè)數(shù)為邊數(shù)),并且每個(gè)更大的環(huán)都會(huì)被計(jì)算兩次,所以最后要減掉.然后就搞定了.
?
代碼:
?
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<vector> using namespace std;long long dp[1<<20][20],ans=0; vector<int> e[20];int lowbit(int x) {return x&(-x); }int main() {int n,m,f,t;scanf("%d%d",&n,&m);for(int i=0;i<m;i++){scanf("%d%d",&f,&t);e[f-1].push_back(t-1);e[t-1].push_back(f-1);}for(int i=0;i<n;i++){dp[1<<i][i]=1;}for(int sta=1;sta<(1<<n);sta++){for(int i=0;i<n;i++){if(dp[sta][i]){for(int k=0;k<e[i].size();k++){int j=e[i][k];if(lowbit(sta)>(1<<j)){continue;}if(sta&(1<<j)){if(lowbit(sta)==(1<<j)){ans+=dp[sta][i];}}else{dp[sta|(1<<j)][j]+=dp[sta][i]; }}}}ans=(ans-m)/2;printf("%lld\n",ans);return 0; }?
?
?
?
?每天刷題,身體棒棒!
?
轉(zhuǎn)載于:https://www.cnblogs.com/stxy-ferryman/p/7637383.html
總結(jié)
以上是生活随笔為你收集整理的CodeForces 11D(状压DP 求图中环的个数)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机基础知识--编码知识
- 下一篇: 10、angular的全部api