Codeforces will not be available in the period 01:00-05:00 May, 30 (MSK, UTC +3) because of maintenance. ×

### the_annoying_'s blog

By the_annoying_, history, 2 months ago, ,

977E - Компоненты-циклы

I always end up getting Memory Limit Exceed whenever I use a graph data structure. I think there is some kind of error in my implementation, which I cannot spot. Can someone help me out with that?

I this problem I have used the same logic as given on https://www.geeksforgeeks.org/number-of-simple-cyclic-components-in-an-undirected-graph/

But I am still getting the Memory limit to exceed. So can somebody help me out?

#include<bits/stdc++.h>
using namespace std;

vector<int> p;    //This vector keeps the curr component that is fetched using dfs.

void dfs(vector<vector<int> > g,bool arr[],int i)
{
arr[i]=true;
p.push_back(i);
for(auto it=g[i].begin();it!=g[i].end();it++)
{
if(!arr[*it])
{
dfs(g,arr,(*it));
}
}
}

int main()
{
int n,m;
cin >> n >> m;
vector<vector<int> > G(n+1);
for(int i=0;i<m;i++)
{
int x,y;
cin >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}

bool vis[n+1];
memset(vis,false,sizeof(vis));

int count = 0;
for(int i=1;i<=n;i++)
{
vector<int> temp;
if(!vis[i])
{
bool flag=true;
dfs(G,vis,i);
for(int i=0;i<p.size();i++)
{
if(G[p[i]].size()!=2)      //Checking if degree is 2 or not!
{
flag=false;
break;
}
}
if(flag)
{
count++;
}
p.clear();
}
}
cout << count << "\n";
return 0;
}



• +3

 » 2 months ago, # |   +11 try sending g by reference by changing dfs(vector g,bool arr[],int i) to dfs(vector &g,bool arr[],int i) when I changed it , it got AC
•  » » 2 months ago, # ^ |   0 Thanks, Man!! I never though a simple pass by reference could change that much! Thanks once again!
•  » » » 2 months ago, # ^ |   +3 I suggest you using Graph as a global variable for running faster. If there are some graphs, just declare them normally globally. But if there are more graphs, using array of graphs is suggested