Checking whether a graph is bipartite using BFS I am solving a simple problem that checks whether a graph is two-colourable (bipartite graph). I am using BFS for this approach using C++ STL. I've replaced cin and cout with scanf and printf as suggested by fellow programmers but still the judge reports TLE.

#include&lt;iostream&gt;
#include&lt;list&gt;
#include&lt;cstring&gt;
#include&lt;cstdio&gt;
using namespace std;
int flag = 1;

class Graph
{
    int V;
    list&lt;int&gt; *adj;

    public:
        Graph(int V);
        void addEdge(int v, int w);
        void BFS(int s);
};

Graph::Graph(int V)
{
    this-&gt;V = V;
    adj = new list&lt;int&gt;[1000001];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w);
    adj[w].push_back(v);
}

void Graph::BFS(int s)
{
    bool *visited = new bool[V];
    string *color = new string[1000001];
    for(int i=0;i&lt;V;i++)
        visited[i] = false;
    list&lt;int&gt; queue;
    queue.push_back(s);
    visited[s] = true;
    color[s] = "red";
    list&lt;int&gt;::iterator i;
    flag = 1;
    while(!queue.empty())
    {
        s = queue.front();
        queue.pop_front();

        for(i = adj[s].begin(); i != adj[s].end(); i++)
        {
            if(!visited[*i])
            {
                visited[*i] = true;
                if(color[s] == "red")
                    color[*i] = "blue";
                if(color[s] == "blue")
                    color[*i] = "red";
                queue.push_back(*i);
            }
            else
            {
                if(color[s] == color[*i])
                    flag = 0;
            }
        }
    }
}


int main()
{
    int T, bugs, edges, from, to;
    scanf("%d", &amp;T);
    int p = T;
    while(T--)
    {
        scanf("%d%d", &amp;bugs, &amp;edges);
        Graph g(bugs+1);
        for(int i=0; i&lt;edges; i++)
        {
            scanf("%d%d", &amp;from, &amp;to);
            g.addEdge(from, to);
        }

        g.BFS(from);

        if(!flag)
            printf("Scenario #%d:\nSuspicious bugs found!\n", p-T);
        else
            printf("Scenario #%d:\nNo suspicious bugs found!\n", p-T);

    }


    return 0;
}
Stop using std::list, which is a doubly linked list and does not support fast random access. You should use std::vector instead, supporting O(1) random access.

Instead of 

list&lt;int&gt; *adj;


You can have a vector of vectors, which will be not only faster, but also memory-leak free.