Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Thursday, February 12, 2015

BUGLIFE-A Bug’s Life

A Bug’s Life


Given below code is for BUGLIFE spoj or A Bug's life spoj.


Explanation : Use simple bfs to find cycle of odd length , or check graph is bipartite or not.


#include <bits/stdc++.h>
using namespace std;
int G[2019][2019]={0,0};
int chec(int a);
int n;
int colorArr[2019];
int main()
{
    int t,m,x,y,i;
    scanf("%d",&t);
    for(int test = 1 ; test <= t ; test++)
    {
        memset(G,0,sizeof(G));
        int flag=0;
        scanf("%d%d",&n,&m);
        for(i=0;i<m;i++)
        {
            scanf("%d%d",&x,&y);
            G[x][y]=1;
            G[y][x]=1;
        }
        int res;
        for ( i = 1; i <= n; i++)
        colorArr[i] = -1;

        for(i=1;i<=n;i++)
        {
            if(colorArr[i]== -1)
            {
                res=chec(i);
                if(res==0)
                {
                    flag=1;
                    break;
                }
            }
        }
        if(flag==1)
            printf("Scenario #%d:\nSuspicious bugs found!\n",test);
        else
            printf("Scenario #%d:\nNo suspicious bugs found!\n",test);
    }
    return 0;
}

int chec(int start)
{   
    colorArr[start] = 1;
 
    queue <int> q;
    q.push(start);
    while (!q.empty())
    {
       
        int i = q.front();
        q.pop();
 
       
        for (int j = 1; j <= n; j++)
        {
            if (G[i][j] && colorArr[j] == -1)
            {
       
                colorArr[j] = 1 - colorArr[i];
                q.push(j);
            }
            else if (G[i][j] && colorArr[j] == colorArr[i])
                return 0;
        }
    }
    return 1;
}

1 comment:

Your comment is valuable to us