How to reduce memory usage when using graphs?

Revision en1, by the_annoying_, 2020-04-01 03:54:55

977E - Cyclic Components

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;
}

Tags #graphs, #cycles

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English the_annoying_ 2020-04-01 03:54:55 1770 Initial revision (published)