Can anyone spot what is wrong with that code? - graph

I have been trying to solve a problem from coursera.
Problem description: Given an undirected graph with š‘› vertices and š‘š edges, check whether it is bipartite.
Input Format. A graph is given in the standard format.
Constraints. 1 ā‰¤ š‘› ā‰¤ 105, 0 ā‰¤ š‘š ā‰¤ 105.
Output Format. Output 1 if the graph is bipartite and 0 otherwise.
Input:
4 4
1 2
4 1
2 3
3 1
Output:
0
Input:
5 4
5 2
4 2
3 4
1 4
Output:
1
I came up with a solution in c++ that looks like
#include <bits/stdc++.h>
using namespace std;
#define vvi vector<vector<int>>
#define vi vector<int>
#define qi queue<int>
int bfs(vvi adj, int s, vi &disc, vi &dist)
{
disc[s] = 1; dist[s] = 0;
qi q;
q.push(s);
while(!q.empty())
{
int u = q.front(); q.pop();
for(int i: adj[u])
{
if(!disc[i])
{
disc[i] = 1;
q.push(i);
dist[i] = dist[u]+1;
}else if(dist[u]==dist[i])
{
return 0;
}
}
}
return 1;
}
bool isBipartite(vvi adj, vi &disc, vi &dist)
{
for(int i=0;i<adj.size();++i)
{
if(!disc[i])
{
if(!bfs(adj, i, disc, dist))
{
return 0;
}
}
}
return 1;
}
int main()
{
int n, m;
cin >> n >> m;
vvi adj(n);
for(int i=0;i<m;++i)
{
int x, y;
cin >> x >> y;
adj[x-1].push_back(y-1);
adj[y-1].push_back(x-1);
}
vi dist(n);
vi disc(n, 0);
cout << isBipartite(adj, disc, dist);
}
But this solution is generating wrong answer on test case 3. Can anyone figure out what I have missed in that code?
Thanks in advance. ā™„

Your logic seems flawless, there is a possible cause of error: you don't pass adj parameter as a reference. This mean that for every call of bfs method the graph will be copied. If 3rd test case is an isolated graph (no edges) that would be bad. Sometimes runtime error and memory exceeded error are treated by the online judge as a non existent wrong answer.

Related

connected components of triangle faces in a mesh

I have a list of vertices and faces which index the vertex:
For example the list of vertices are (x,y,z) :
0 1 0
1 1 1
2 0 1
3 0 0
1 1 2
...
...
...
Faces that index the vertex:
0 1 2
2 3 4
4 0 1
...
...
...
With the list of faces I need to group them up for those that faces are connected to each other. For the first 3 faces I know that they are connected to each other as they have common index. How do I implement an algorithm to do this? thanks.
I use the method from this link using depth first search to visit all the node but gets a segmentation fault inside the class
https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
#include <bits/stdc++.h>
using namespace std;
class Graph {
// A function used by DFS
void DFSUtil(int v);
public:
int count;
map<int, bool> visited;
map<int, list<int> > adj;
// function to add an edge to graph
void addEdge(int v, int w);
// prints DFS traversal of the complete graph
void DFS();
};
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to vā€™s list.
}
void Graph::DFSUtil(int v)
{
// Mark the current node as visited and print it
visited[v] = true;
cout << v << " ";
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFSUtil(*i);
}
// The function to do DFS traversal. It uses recursive
// DFSUtil()
void Graph::DFS()
{
count = 0;
// Call the recursive helper function to print DFS
// traversal starting from all vertices one by one
for (auto i : adj)
if (visited[i.first] == false)
{
DFSUtil(i.first);
count++;
}
}
int main()
{
// Create a graph given in the above diagram
Graph g;
for face in faces :
{
g.addEdge(face[0], face[1]);
g.addEdge(face[0], face[2]);
g.addEdge(face[1], face[0]);
g.addEdge(face[1], face[2]);
g.addEdge(face[2], face[0]);
g.addEdge(face[2], face[1]);
}
cout << "Following is Depth First Traversal \n";
// Function call
g.DFS();
cout << "number of connected components = " << g.count << "\n";
return 0;
}

What is an algorithm to generate the following sequence?

I want to find out the function to generate the sequence with the following pattern.
1 2 3 1 1 2 2 3 3 1 1 1 1 2 2 2 2 3 3 3 3 ....
Where the lower bound number is 1 upper number bound number is 3. Each time numbers start from 1 and each number repeats 2 ^ n times, with n starting with 0.
Here it goes, I hope it will help.
#include <iostream>
#include <math.h>
int main(){
for(int n = 0; n < 5;n++){
for(int i = 1; i < 4;i++){
for(int j = 0;j < pow(2,n) ;j++){
std::cout << i;
}
}
}
return 0;
}
Here is a code in C++:
#include <iostream>
#include <cmath>
int main()
{
// These are the loop control variables
int n, m, i, j, k;
// Read the limit
cin >> n;
// Outermost loop to execute the pattern {1..., 2..., 3...} n times
for (i = 0; i < n; ++i)
{
// This loop generates the required numbers 1, 2, and 3
for (j = 1; j <= 3; ++j)
{
// Display the generated number 2^i times
m = pow(2, i);
for (k = 0; k < m; ++k)
{
std::cout << j << ' ';
}
}
}
}
You can use the same logic in any language you choose to implement it.

Converting grid coordinates

So I have a grid which is in one form and im trying to get the X and Y.
Is there a formula where I could turn for example 12 into 2,2 or 14 to 2,3
Also is there a name for this type of grid?
static int getX(int z)
{
int count = 0;
int res = 0;
int curr = 0;
for(int temp = z; temp > 0; temp >>= 1)
{
if(count % 2 ==0)
{
res += ((temp & 1) << curr);
curr++;
}
count++;
}
return res;
}
static int getY(int z)
{
int count = 0;
int res = 0;
int curr = 0;
for(int temp = z; temp > 0; temp >>= 1)
{
if(count % 2 ==1)
{
res += ((temp & 1) << curr);
curr++;
}
count++;
}
return res;
}
As Sneftel observed, this looks like a Z-order curve. As such, you can convert coordinates by interleaving binary representations. So your examples are
0 1 0 x=2 0 1 0 x=2
0 1 0 y=2 0 1 1 y=3
001100 p=12 001110 p=14
So to get x and y coordinates from the cell number p, you assign the bits of p alternatingly to x and y. This kind of bit arithmetic is pretty hard to express using elementary arithmetic operations, and there is no generally recognized formula symbol for this that I'm aware of, but the idea is quite simple.

caught segfault, memory not mapped error in Rcpp trying to implement a function

i'm new in Rcpp and i dont really know Rcpp. but as a personal project, i was trying to run some sort algorithms using some C code that i had, converting them to R with Rcpp.
But i'm getting the memory not mapped error, and i dont really understand what i'm doing wrong, so if someone could enlighten me :)
The problem happens when a try the following code
#include <Rcpp.h>
using namespace Rcpp;
void intercala(int p, int q, int r, NumericVector v)
{
int i, j, k;
NumericVector w = NumericVector::create();
i = p;
j = q;
k = 0;
while (i < q && j < r) {
if (v[i] < v[j]) {
w[k] = v[i];
i++;
}
else {
w[k] = v[j];
j++;
}
k++;
}
while (i < q) {
w[k] = v[i];
i++;
k++;
}
while (j < r) {
w[k] = v[j];
j++;
k++;
}
for (i = p; i < r; i++)
v[i] = w[i-p];
}
void mergesort(int p, int r, NumericVector v)
{
int q;
if (p < r - 1) {
q = (p + r) / 2;
mergesort(p, q, v);
mergesort(q, r, v);
intercala(p, q, r, v);
}
}
// [[Rcpp::export]]
NumericVector mergesortC(NumericVector vetor) {
int n = vetor.size();
mergesort(0,n,vetor);
return vetor;
}
This code is in a file called merge.cpp
Them when i try to run on R
> library(Rcpp)
> sourceCpp("merge.cpp")
> vetor<-sample(1:10)
> vetor
[1] 1 5 7 4 3 8 9 2 10 6
> mergesortC(vetor)
[1] 1 2 3 4 5 6 7 8 9 10
> vetor
*** caught segfault ***
address 0x8, cause 'memory not mapped'
Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace
Selection:
It seems to me that i'm doing something that i shouldn't, but the code seem to work in the begin, then i somehow mess with the memory in the object vetor. I managed to work on other algorithms with Rcpp, but this one wont work, and i dont understand what i'm doing wrong, so if anyone could spare a moment.

Turbo C++ 2D array allocation

enter code here![I'm using Turbo c++....whenever I assign values for a 2d array and try to display them....atleast one of the rows (or all of them) of the array won't be allocated with the proper values the user has entered. I ignored this because when the program was made to run for the 2nd time, it worked fine! But now array allocation itself isnt working properly. compiler error?
PROGRAM.... i've entered 5 rows and 2 column values....
for eg.
1 2
2 5
3 6
5 8
4 7
the above are inputs...
the output should be same as well...but it shows...
1 2
2 5
4 7
4 7
4 7
p.s. I know only to work with Turbo c++...so please dont suggest Dev c++
As a newbie, I could use some help. thanks!
THE CODE IS AS FOLLOWS
` #include
#include
void main()
{
float **arr;
cout<<"rows : ";
cin>>SIZE;
cout<<"col : ";
cin>>n;
arr=new float *[SIZE];
for(int Di=0;Di<n;Di++)
{
arr[Di]=new float[n];
}
cout<<"enter...";
for(int i=0;i<(SIZE);i++)
{
cout<<"\n";
for(int j=0;j<n;j++)
{
cout<<"\t";
cin>>arr[i][j];
}
}
for(int ii=0;ii<SIZE;ii++)
{
cout<<"\n";
for(int jj=0;jj<n;jj++)
{
cout<<"\t";
cout<<arr[ii][jj];
}
}
getch();
}`
The program allocates n rows instead of SIZE rows.
You want the loop
for (int Di = 0; Di < n; Di++)
to read
for (int Di = 0; Di < SIZE; Di++)

Resources