BUGLIFE - A Bug’s Life - SPOJ Solution C++

  Problem Link : BUGLIFE  


👉 Hint : Find cycle in graph

 


✅ C++ Solution :

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

vector<int> adj[2001];
bool visited[2001];
int cnt[2001];
bool flag=0;
void dfs(int v,int par)
{
	visited[v]=1;
	for(int i=0;i<adj[v].size();i++)
	{
		if(!visited[adj[v][i]])
		{
			cnt[adj[v][i]]=cnt[v]+1;
			dfs(adj[v][i],v);
		}
		else if(adj[v][i]!=par)
		{
			if ((cnt[v]-cnt[adj[v][i]]+1)%2==1)
			    flag=1;
		}
	}
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int sc;
	cin>>sc;
	for(int s=1;s<=sc;s++)
	{
	    flag=0;
		int n,m,x,y;
		cin>>n>>m;
		memset(visited,0,sizeof(visited));
		memset(cnt,0,sizeof(cnt));
	
		for(int i=1;i<=n;i++)
			adj[i].clear();
		for(int i=1;i<=m;i++)
		{
		    cin>>x>>y;
		    adj[x].push_back(y);
		    adj[y].push_back(x);
		}	
		for(int i=1;i<=n;i++)
		{
			if(!visited[i])
			{
				cnt[i]=1;
				dfs(i,-1);
			}
		}
		if(flag==1)
		    cout<<"Scenario #"<<s<<":"<<endl<<"Suspicious bugs found!"<<endl;
		else
		    cout<<"Scenario #"<<s<<":"<<endl<<"No suspicious bugs found!"<<endl;
	}
}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!