random undirected conected graph with even vertex degree - c++

I need to create random conected undirected graph with even vertex degrees. I have to do that to test the times of finding Euler cycles for different vertex number (N). The representation of the graph is adjacency list. I have such code:
void make_graph()
{
int i,a,b,c;
int nasycenie;
nasycenie=(0.5)*((N*(N-1))/2);
if(nasycenie<N-1) nasycenie=N-1;
for(i=1;i<=nasycenie;++i)
{
if(i<N)
{
a=rand()%i;
b=i;
}
else
{
a=rand()%N;
b=rand()%(N-1);
b+=(b>=a);
}
L1[a].push_back(b);
L1[b].push_back(a);
}
}
It makes connected undirected graph but vertex degrees aren't even. How to improve that to have even vertex degrees?

This code will create the graph you specified , but in AdjacencyMatrix (only half a matrix actulay, since graph is undirect) presentation , it wouldn't be hard to turn it into an AdjacencyList.
bool[vNum][vNum] make_graph(int vNum)
{
bool[vNum][vNum] adjacency;
int edgeNum = rand()%C(vNum , 2);
for(int i=0 ; i<vNum; i++)
{
int j=0;
for(j ; j<i; j++)
{
adjacency[i][j] = rand()%2;
}
if(hasOddTrue(adjacency[i] , j))
{
int selectedIndex = rand()%j;
adjacency[i][selectedIndex ] = !adjacency[i][selectedIndex ];
}
}
return adjacency;
}
bool hasOddTrue(bool[] list , int length)
{
bool b = false;
for(int i=0 ; i<length ; i++) { b = xor(b, list[i]); }
return b;
}

Related

How to write code for Breadth-first search in C++

I have been trying to do a graph search for a problem from Hackerrank. Lastly, I have come up with
#include <cstdio>
#include <list>
using namespace std;
void bfs(list<int> adjacencyList[], int start, int countVertices) {
// initialize distance[]
int distance[countVertices];
for(int i=0;i < countVertices; i++) {
distance[i] = -1;
}
list<int>::iterator itr;
int lev = 0;
distance[start-1] = lev; // distance for the start vertex is 0
// using start -1 since distance is array which are 0-indexed
list<int> VertexQueue;
VertexQueue.push_back(start);
while(!VertexQueue.empty()) {
int neighbour = VertexQueue.front();
itr = adjacencyList[neighbour].begin();
while(itr != adjacencyList[neighbour].end()) {
int vertexInd = (*itr) - 1;
if(distance[vertexInd] == -1) { // a distance of -1 implies that the vertex is unexplored
distance[vertexInd] = (lev + 1) * 6;
VertexQueue.push_back(*itr);
}
itr++;
}
VertexQueue.pop_front();
lev++;
}
// print the result
for(int k=0;k< countVertices;k++) {
if (k==start-1) continue; // skip the start node
printf("%d ",distance[k]);
}
}
int main() {
int countVertices,countEdges,start,T,v1,v2;
scanf("%d", &T);
for(int i=0; i<T; i++) {
scanf("%d%d", &countVertices,&countEdges);
list<int> adjacencyList[countVertices];
// input edges in graph
for(int j=0; j<countEdges; j++) {
scanf("%d%d",&v1,&v2);
adjacencyList[v1].push_back(v2);
adjacencyList[v2].push_back(v1); // since the graph is undirected
}
scanf("%d",&start);
bfs(adjacencyList, start, countVertices);
printf("\n");
}
return 0;
}
However, this is resulting in 'Segmentation Fault' and I cannot figure out where I am going wrong.
Also, I have comes across segmentation fault a lot of times, but have no idea how to debug it. Would be great if someone can give me an idea of that.
scanf("%d%d", &countVertices,&countEdges);
list<int> adjacencyList[countVertices];
Above code appears wrong. If your indices start with 1, either make adjacencyList of size countVertices + 1 or decrease u and v before putting them in the list.
You can also use a (an unordered) map mapping vertex to a list which will not segfault.
Also not that VLA are not part of standard C++, so avoid them even if your compiler support them as extension.

Minimum distance between two nodes in tree

Given a unweighted and undirected tree with N nodes and N-1 edges I need to find minimum distance between source S and destination D.
Code :
vector<vector<int> >G(110);
bool check(int node,vector<int>path)
{
for(int i=0;i<path.size();++i)
{
if(path[i]==node)
return false;
}
return true;
}
int findMinpath(int source,int target,int totalnode,int totaledge)
{
vector<int>path;
path.push_back(source);
queue<vector<int> >q;
q.push(path);
while(!q.empty())
{
path=q.front();
q.pop();
int lastNode=path[path.size()-1];
if(lastNode==target)
{
return path.size()-1;
}
for(int i=0;i<G[lastNode].size();++i){
if(check(G[lastNode][i],path)){
vector<int>new_path(path.begin(),path.end());
new_path.push_back(G[lastNode][i]);
q.push(new_path);
}}}
return 1;
}
And then in main :
int N,S,E;
cin>>N>>S>>E;
for(int i=1;i<=N-1;++i)
{
int u,v;
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
cout<<findpaths(S,E,N,N-1)<<"\n";
Can it be further optimised as I need just minimum distance between S and E
You seem to be pushing vectors to your queue, each vector containing the actual path so far. But you can get away with only pushing nodes, since you only use the last node in those vectors anyway, and instead store the distance to each node from the source.
This will be much faster because you won't be copying vectors at each step.
Keep track of the distances in an array and also use them to make sure you don't visit a node multiple times.
Untested, but should get the point across:
int distance[110 + 1]; // d[i] = distance from source to i, initialize with a large number
int findMinpath(int source,int target,int totalnode,int totaledge)
{
for (int i = 0; i <= totalnode; ++i)
{
distance[i] = 2000000000;
}
queue<int> q;
q.push(source);
distance[source] = 0;
while(!q.empty())
{
node=q.front();
q.pop();
if(node==target)
{
return distance[node];
}
for(int i=0;i<G[node].size();++i){
if(distance[node] + 1 < distance[ G[node][i] ]){
distance[ G[node][i] ] = distance[node] + 1
q.push(G[node][i]);
}}}
return 1;
}

How to print MaxPath of graph using dfs O(n)?

We want to find the farthest vertex to the i-th vertex,
farthest vertex to the current vertex of graph, gives the maximum Path to us.
Please help me to get this right:
vector<int> v[100];
bool mark[100];
int v1;
inline int max_path(int k)
{
int result = -1;
mark[k] = true;
for(int i=0; i<v[k].size(); i++)
if(!mark[v[k][i]])
{
int x = max_path(v[k][i]);
if(x > result)
{
result = x;
v1 = v[k][i];
}
}
return result+1;
}
v1 must be the farthest vertex to the current vertex (k), and result must be the length of the path.
You can use int result[n] and then print the max var of that...

What is an efficient way to sort a graph?

For example suppose there are 3 nodes A,B,C and A links to B and C, B links to A and C, and C links to B and A. In visual form its like this
C <- A -> B //A links to B & C
A <- B -> C //B links to A & C
B <- C -> A //C links to B & A
Assume the A,B,C are held in an array like so [A,B,C] with index starting at 0. How can I efficiently sort the array [A,B,C] according to the value held by each node.
For example if A holds 4, B holds -2 and C holds -1, then sortGraph([A,B,C]) should return [B,C,A]. Hope its clear. Would it be possible if I can somehow utilize std::sort?
EDIT: Not basic sort algorithm. Let me clarify a bit more. Assume I have a list of Nodes [n0,n1...nm]. Each ni has a left and right neighbor index. For example, n1 left neight is n0 and its right neighbor is n2. I use index to represent the neighbor. If n1 is at index 1, then its left neighbor is at index 0 and its right neighbor is at index 2. If I sort the array, then I need to update the neighbor index as well. I don't want to really implement my own sorting algorithm, any advice on how to proceed?
If I understand the edited question correctly your graph is a circular linked list: each node points to the previous and next nodes, and the "last" node points to the "first" node as its next node.
There's nothing particularly special you need to do the sort that you want. Here are the basic steps I'd use.
Put all the nodes into an array.
Sort the array using any sorting algorithm (e.g. qsort).
Loop through the result and reset the prev/next pointers for each node, taking into account the special cases for the first and last node.
Here is a C++ implementation, hope is useful (it includes several algorithms like dijkstra, kruskal, for sorting it uses depth first search, etc...)
Graph.h
#ifndef __GRAPH_H
#define __GRAPH_H
#include <vector>
#include <stack>
#include <set>
typedef struct __edge_t
{
int v0, v1, w;
__edge_t():v0(-1),v1(-1),w(-1){}
__edge_t(int from, int to, int weight):v0(from),v1(to),w(weight){}
} edge_t;
class Graph
{
public:
Graph(void); // construct a graph with no vertex (and thus no edge)
Graph(int n); // construct a graph with n-vertex, but no edge
Graph(const Graph &graph); // deep copy of a graph, avoid if not necessary
public:
// #destructor
virtual ~Graph(void);
public:
inline int getVertexCount(void) const { return this->numV; }
inline int getEdgeCount(void) const { return this->numE; }
public:
// add an edge
// #param: from [in] - starting point of the edge
// #param: to [in] - finishing point of the edge
// #param: weight[in] - edge weight, only allow positive values
void addEdge(int from, int to, int weight=1);
// get all edges
// #param: edgeList[out] - an array with sufficient size to store the edges
void getAllEdges(edge_t edgeList[]);
public:
// topological sort
// #param: vertexList[out] - vertex order
void sort(int vertexList[]);
// dijkstra's shortest path algorithm
// #param: v[in] - starting vertex
// #param: path[out] - an array of <distance, prev> pair for each vertex
void dijkstra(int v, std::pair<int, int> path[]);
// kruskal's minimum spanning tree algorithm
// #param: graph[out] - the minimum spanning tree result
void kruskal(Graph &graph);
// floyd-warshall shortest distance algorithm
// #param: path[out] - a matrix of <distance, next> pair in C-style
void floydWarshall(std::pair<int, int> path[]);
private:
// resursive depth first search
void sort(int v, std::pair<int, int> timestamp[], std::stack<int> &order);
// find which set the vertex is in, used in kruskal
std::set<int>* findSet(int v, std::set<int> vertexSet[], int n);
// union two sets, used in kruskal
void setUnion(std::set<int>* s0, std::set<int>* s1);
// initialize this graph
void init(int n);
// initialize this graph by copying another
void init(const Graph &graph);
private:
int numV, numE; // number of vertices and edges
std::vector< std::pair<int, int> >* adjList; // adjacency list
};
#endif
Graph.cpp
#include "Graph.h"
#include <algorithm>
#include <map>
Graph::Graph()
:numV(0), numE(0), adjList(0)
{
}
Graph::Graph(int n)
:numV(0), numE(0), adjList(0)
{
this->init(n);
}
Graph::Graph(const Graph &graph)
:numV(0), numE(0), adjList(0)
{
this->init(graph);
}
Graph::~Graph()
{
delete[] this->adjList;
}
void Graph::init(int n)
{
if(this->adjList){
delete[] this->adjList;
}
this->numV = n;
this->numE = 0;
this->adjList = new std::vector< std::pair<int, int> >[n];
}
void Graph::init(const Graph &graph)
{
this->init(graph.numV);
for(int i = 0; i < numV; i++){
this->adjList[i] = graph.adjList[i];
}
}
void Graph::addEdge(int from, int to, int weight)
{
if(weight > 0){
this->adjList[from].push_back( std::make_pair(to, weight) );
this->numE++;
}
}
void Graph::getAllEdges(edge_t edgeList[])
{
int k = 0;
for(int i = 0; i < numV; i++){
for(int j = 0; j < this->adjList[i].size(); j++){
// add this edge to edgeList
edgeList[k++] = edge_t(i, this->adjList[i][j].first, this->adjList[i][j].second);
}
}
}
void Graph::sort(int vertexList[])
{
std::pair<int, int>* timestamp = new std::pair<int, int>[this->numV];
std::stack<int> order;
for(int i = 0; i < this->numV; i++){
timestamp[i].first = -1;
timestamp[i].second = -1;
}
for(int v = 0; v < this->numV; v++){
if(timestamp[v].first < 0){
this->sort(v, timestamp, order);
}
}
int i = 0;
while(!order.empty()){
vertexList[i++] = order.top();
order.pop();
}
delete[] timestamp;
return;
}
void Graph::sort(int v, std::pair<int, int> timestamp[], std::stack<int> &order)
{
// discover vertex v
timestamp[v].first = 1;
for(int i = 0; i < this->adjList[v].size(); i++){
int next = this->adjList[v][i].first;
if(timestamp[next].first < 0){
this->sort(next, timestamp, order);
}
}
// finish vertex v
timestamp[v].second = 1;
order.push(v);
return;
}
void Graph::dijkstra(int v, std::pair<int, int> path[])
{
int* q = new int[numV];
int numQ = numV;
for(int i = 0; i < this->numV; i++){
path[i].first = -1; // infinity distance
path[i].second = -1; // no path exists
q[i] = i;
}
// instant reachable to itself
path[v].first = 0;
path[v].second = -1;
while(numQ > 0){
int u = -1; // such node not exists
for(int i = 0; i < numV; i++){
if(q[i] >= 0
&& path[i].first >= 0
&& (u < 0 || path[i].first < path[u].first)){ //
u = i;
}
}
if(u == -1){
// all remaining nodes are unreachible
break;
}
// remove u from Q
q[u] = -1;
numQ--;
for(int i = 0; i < this->adjList[u].size(); i++){
std::pair<int, int>& edge = this->adjList[u][i];
int alt = path[u].first + edge.second;
if(path[edge.first].first < 0 || alt < path[ edge.first ].first){
path[ edge.first ].first = alt;
path[ edge.first ].second = u;
}
}
}
delete[] q;
return;
}
// compare two edges by their weight
bool edgeCmp(edge_t e0, edge_t e1)
{
return e0.w < e1.w;
}
std::set<int>* Graph::findSet(int v, std::set<int> vertexSet[], int n)
{
for(int i = 0; i < n; i++){
if(vertexSet[i].find(v) != vertexSet[i].end()){
return vertexSet+i;
}
}
return 0;
}
void Graph::setUnion(std::set<int>* s0, std::set<int>* s1)
{
if(s1->size() > s0->size()){
std::set<int>* temp = s0;
s0 = s1;
s1 = temp;
}
for(std::set<int>::iterator i = s1->begin(); i != s1->end(); i++){
s0->insert(*i);
}
s1->clear();
return;
}
void Graph::kruskal(Graph &graph)
{
std::vector<edge_t> edgeList;
edgeList.reserve(numE);
for(int i = 0; i < numV; i++){
for(int j = 0; j < this->adjList[i].size(); j++){
// add this edge to edgeList
edgeList.push_back( edge_t(i, this->adjList[i][j].first, this->adjList[i][j].second) );
}
}
// sort the list in ascending order
std::sort(edgeList.begin(), edgeList.end(), edgeCmp);
graph.init(numV);
// create disjoint set of the spanning tree constructed so far
std::set<int>* disjoint = new std::set<int>[this->numV];
for(int i = 0; i < numV; i++){
disjoint[i].insert(i);
}
for(int e = 0; e < edgeList.size(); e++){
// consider edgeList[e]
std::set<int>* s0 = this->findSet(edgeList[e].v0, disjoint, numV);
std::set<int>* s1 = this->findSet(edgeList[e].v1, disjoint, numV);
if(s0 == s1){
// adding this edge will make a cycle
continue;
}
// add this edge to MST
graph.addEdge(edgeList[e].v0, edgeList[e].v1, edgeList[e].w);
// union s0 & s1
this->setUnion(s0, s1);
}
delete[] disjoint;
return;
}
#define IDX(i,j) ((i)*numV+(j))
void Graph::floydWarshall(std::pair<int, int> path[])
{
// initialize
for(int i = 0; i < numV; i++){
for(int j = 0; j < numV; j++){
path[IDX(i,j)].first = -1;
path[IDX(i,j)].second = -1;
}
}
for(int i = 0; i < numV; i++){
for(int j = 0; j < this->adjList[i].size(); j++){
path[IDX(i,this->adjList[i][j].first)].first
= this->adjList[i][j].second;
path[IDX(i,this->adjList[i][j].first)].second
= this->adjList[i][j].first;
}
}
// dynamic programming
for(int k = 0; k < numV; k++){
for(int i = 0; i < numV; i++){
for(int j = 0; j < numV; j++){
if(path[IDX(i,k)].first == -1
|| path[IDX(k,j)].first == -1){
// no path exist from i-to-k or from k-to-j
continue;
}
if(path[IDX(i,j)].first == -1
|| path[IDX(i,j)].first > path[IDX(i,k)].first + path[IDX(k,j)].first){
// there is a shorter path from i-to-k, and from k-to-j
path[IDX(i,j)].first = path[IDX(i,k)].first + path[IDX(k,j)].first;
path[IDX(i,j)].second = k;
}
}
}
}
return;
}
If you are looking for sorting algorithms you should just ask google:
http://en.wikipedia.org/wiki/Sorting_algorithm
My personal favourite is the BogoSort coupled with parallel universe theory. The theory is that if you hook a machine up to the program that can destroy the universe, then if the list isn't sorted after one iteration it will destroy the universe. That way all the parallel universes except the one with the list sorted will be destroyed and you have a sorting algorithm with complexity O(1).
The best ....
Create a struct like this:
template<typename Container, typename Comparison = std::less<typename Container::value_type>>
struct SortHelper
{
Container const* container;
size_t org_index;
SortHelper( Container const* c, size_t index ):container(c), org_index(index) {}
bool operator<( SortHelper other ) const
{
return Comparison()( (*c)[org_index], (*other.c)[other.org_index] );
}
};
This lets you resort things however you want.
Now, make a std::vector<SortHelper<blah>>, sort it, and you now have a vector of instructions of where everything ends up going after you sort it.
Apply these instructions (there are a few ways). An easy way would be to reuse container pointer as a bool. Walk the sorted vector of helpers. Move the first entry to where it should go, moving what you found where it should go to where it should go, and repeat until you loop or the entire array is sorted. As you go, clear the container pointers in your helper struct, and check them to make sure you don't move an entry that has already been moved (this lets you detect loops, for example).
Once a loop has occurred, proceed down the vector looking for the next as-yet-not-in-right-place entry (with a non-null container pointer).

BFS to check if a graph is bipartite in c++

I am implementing an algorithm to determine whether an undirected graph is bipartite or not. Based on this pseudo-code made ​​my implementation, which works for graphs connected, but when it is disconnected simply the program indicates a wrong answer. I think if its not connected, then one more loop is needed for every disjoint sub-graph. But im stuck with this. How I can solve my code for me to print a correct answer?
#include <cstdio>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
#define MAX 1000
int numberVertex, numberEdges;
int particion[MAX], visited[MAX];
vector< int > adjacencyMatrix[MAX];
bool bfs()
{
int i, origin, destination, begin;
queue< int > queueVertex;
begin = 0;
queueVertex.push(begin);
particion[begin] = 1; // 1 left,
visited[begin] = 1; // set adjacencyMatrixray
while(!queueVertex.empty())
{
origin = queueVertex.front(); queueVertex.pop();
for(i=0; i < adjacencyMatrix[origin].size(); i++)
{
destination = adjacencyMatrix[origin][i];
if(particion[origin] == particion[destination])
{
return false;
}
if(visited[destination] == 0)
{
visited[destination] = 1;
particion[destination] = 3 - particion[origin]; // alter 1 and 2 subsets
queueVertex.push(destination);
}
}
}
return true;
}
int main()
{
freopen("tarea2.in", "r", stdin);
int i,j, nodeOrigin, nodeDestination;
scanf("%d %d", &numberVertex, &numberEdges);
for(i=0; i<numberEdges; i++)
{
scanf("%d %d", &nodeOrigin, &nodeDestination);
adjacencyMatrix[nodeOrigin].push_back(nodeDestination);
adjacencyMatrix[nodeDestination].push_back(nodeOrigin);
}
if(bfs()) {
printf("Is bipartite\n");
for (j=0; j<numberVertex; j++){
cout<<j<<" "<<particion[j]<<endl;
}
}
else {printf("Is not bipartite\n");}
return 0;
}
For example for this input
6 4
3 0
1 0
2 5
5 4
the output should be:
Is bipartite
0 1
1 2
2 1
3 2
4 1
5 2
Instead throws me the output:
0 1
1 2
2 0
3 2
4 0
5 0
This happens because the graph is not a connected graph, ie, has two connected components.I hope you can help me because I've been stuck with this for several days.
You should run bfs on every connected component. Simplest way to do this is to iterate over all vertices and if they weren't visited, then just call bfs on them.
bool is_bipartite()
{
for(int i = 0; i < numberVertex; i++)
{
if (visited[i] == 0 && !bfs(i)) {
return false;
}
}
return true;
}
It is still linear because, you run bfs on every connected component once.
#include <cstdio>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
#define MAX 1000
int numberVertex, numberEdges;
int particion[MAX], visited[MAX];
vector< int > adjacencyMatrix[MAX];
bool bfs(int begin)
{
int i, origin, destination;
queue< int > queueVertex;
queueVertex.push(begin);
particion[begin] = 1; // 1 left,
visited[begin] = 1; // set adjacencyMatrixray
while(!queueVertex.empty())
{
origin = queueVertex.front(); queueVertex.pop();
for(i=0; i < adjacencyMatrix[origin].size(); i++)
{
destination = adjacencyMatrix[origin][i];
if(particion[origin] == particion[destination])
{
return false;
}
if(visited[destination] == 0)
{
visited[destination] = 1;
particion[destination] = 3 - particion[origin]; // alter 1 and 2 subsets
queueVertex.push(destination);
}
}
}
return true;
}
bool is_bipartite()
{
for(int i=0; i< numberVertex; i++)
{
if (visited[i] == 0 && !bfs(i)) {
return false;
}
}
return true;
}
int main()
{
//freopen("tarea2.in", "r", stdin);
int i,j, nodeOrigin, nodeDestination;
scanf("%d %d", &numberVertex, &numberEdges);
for(i=0; i<numberEdges; i++)
{
scanf("%d %d", &nodeOrigin, &nodeDestination);
adjacencyMatrix[nodeOrigin].push_back(nodeDestination);
adjacencyMatrix[nodeDestination].push_back(nodeOrigin);
}
if(is_bipartite()) {
printf("Is bipartite\n");
for (j=0; j<numberVertex; j++){
cout<<j<<" "<<particion[j]<<endl;
}
}
else {printf("Is not bipartite\n");}
return 0;
}
The detailed implementation is as follows (C++ version). It will be able to handle several separated connected components.
Assume the graph node is defined as:
struct NODE
{
int color;
vector<int> neigh_list;
};
Then you can check whether the whole graph is bipartite by calling bfs().
bool checkAllNodesVisited(NODE *graph, int numNodes, int & index);
bool bfs(NODE * graph, int numNodes)
{
int start = 0;
do
{
queue<int> Myqueue;
Myqueue.push(start);
graph[start].color = 0;
while(!Myqueue.empty())
{
int gid = Myqueue.front();
for(int i=0; i<graph[gid].neigh_list.size(); i++)
{
int neighid = graph[gid].neigh_list[i];
if(graph[neighid].color == -1)
{
graph[neighid].color = (graph[gid].color+1)%2; // assign to another group
Myqueue.push(neighid);
}
else
{
if(graph[neighid].color == graph[gid].color) // touble pair in the same group
return false;
}
}
Myqueue.pop();
}
} while (!checkAllNodesVisited(graph, numNodes, start)); // make sure all nodes visited
// to be able to handle several separated graphs, IMPORTANT!!!
return true;
}
bool checkAllNodesVisited(NODE *graph, int numNodes, int & index)
{
for (int i=0; i<numNodes; i++)
{
if (graph[i].color == -1)
{
index = i;
return false;
}
}
return true;
}
Bipartite graph is also known as 2-colour graph i.e we can colour all the nodes of the bipartite graph with only 2 colour such that no 2 adjacent node have same colour.
Initially let all vertex are not having any colour.
Start with any vertex and colour it with RED. Then Colour its all adjacent vertices with a colour other than RED let say Black.
Keep on repeating this
till all node are coloured. If at any point you found two adjacent
node have same colour. Then it is not a bipartite graph.
C++ Implementation