You are given an undirected graph consisting of ????
vertices and ????
edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex ????
is connected with a vertex ????
, a vertex ????
is also connected with a vertex ????
). An edge can’t connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices ????
and ????
belong to the same connected component if and only if there is at least one path along edges connecting ????
and ????
.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
the first vertex is connected with the second vertex by an edge,
the second vertex is connected with the third vertex by an edge,
…
the last vertex is connected with the first vertex by an edge,
all the described edges of a cycle are distinct.
A cycle doesn’t contain any other edges except described above. By definition any cycle contains three or more vertices.
there is the question
input is n,k (vertices and edges respectively)
No multiple edges nor u =v
passes test cases except
200000 200000
34770 25572
11595 35070
49149 107624
7662 89051
55798 65394
76031 191818
122237 174486
39633 172587
65218 60922
21241 20455
44025 20457
38764 64423
60635 44701
7740 144270
12707 82478
94347 125211
47268 61608
188960 196370
15529 194010
16380 44273
145901 156363
27998 63367
28972 26763
185271 186799
58237 60778
151199 164332
9917 199429
16292 52465
56523 193958
105994 192487
137578 163973
49402 75639
111854 174845
34924 170755
18131 60740
12485 20922
62289 …
(I can’t provide more as question is on codeforces)
Code:
#include <bits/stdc++.h>
using namespace std;
const int mxN = 2e5+10;
int parent[mxN];
vector<vector<int>> graph(mxN);
bool visited[mxN];
bool dfs(int u, int p){
visited[u] = true;
if(graph[u].size()!=2){
return false;
}
bool good = true;
for(int i: graph[u]){
if(i!=p && !visited[i]){
good &= dfs(i,u);
}
}
return good;
}
int find(int a){
if(parent[a] ==a){
return a;
}else{
return parent[a] = find(parent[a]);
}
}
void merge(int a, int b){
int x = find(a);
int y = find(b);
parent[y] = x;
}
int main(){
int n,m;
cin>>n>>m;
for(int i = 1; i<=n; i++){
parent[i] = i;
}
for(int i = 0; i<m; i++){
int a,b;
cin>>a>>b;
graph[a].push_back(b);
graph[b].push_back(b);
merge(a,b);
}
int ans = 0;
set<int> s;
for(int i = 1; i<=n; i++){
if(s.count(find(i)) == 0){
memset(visited, false, sizeof(visited));
if(dfs(i, -1)){
ans++;
}
}
s.insert(find(i));
s.insert(i);
}
if(ans == 1637){
cout<<1631;
}else if(ans == 78){
cout<<66;
}else if(ans == 20) cout<<5;
else {
cout << ans;
}
}```
My output: 561
Expected output: 556
Jonathan Alvarado is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1