Codeforces 479【E】div3

题目链接:http://codeforces.com/problemset/problem/977/E

题意:就是给你相连边,让你求图内有几个环。

题解:我图论很差,一般都不太会做图论的题。QAQ看官方题解过的。大概就是如果这是一个环的话,每一个点的度数都应该是2才对,根据这个进行dfs做标记。

就算是个简单图论,看到还是会一脸懵逼。QWQ。以后还是会多多写dfs和图论啦。不过个人还是更喜欢数论什么的。

 1 #include<iostream>
 2 #include<vector>
 3 using namespace std;
 4 const int maxn = 200005;
 5 
 6 vector<int> g[maxn];
 7 bool vis[maxn];
 8 int flag;
 9 
10 void dfs(int x){
11     if(vis[x])
12         return ;
13     if(g[x].size() != 2){
14         flag = 1;
15     }
16     vis[x] = true;
17     for(int i = 0; i < g[x].size() ;i++){
18         dfs(g[x][i]);
19     }
20     
21 }
22 
23 int main(){
24     int n,m;
25     cin>>n>>m;
26     while(m--){
27         int x,y;
28         cin>>x>>y;
29         g[x].push_back(y);
30         g[y].push_back(x);
31     }
32     int ans = 0;
33     for(int i = 1; i <= n ;i++){
34         if(!vis[i]){
35             flag = 0;
36             dfs(i);
37             if(flag == 0){
38                 ans++;
39             }
40         }
41     }
42     cout<<ans<<endl;
43     return 0;
44 } 
View Code
原文地址:https://www.cnblogs.com/Asumi/p/9007616.html