Implementing Prim's Algorithm-Logical Error - algorithm

I have been implementing prim's algorithm in c++, but I am not able to figure out why my algorithm is giving the wrong output.
Input Format: The first line has number of Test cases T.For each test case, Number of vertices and Number of edges are given in next line.For the Number of edges, each line consists of 3 numbers a,b,w where there is an undirected,weighted edge between vertices a and b with weight w.
Below is my code :
#include <bits/stdc++.h>
using namespace std;
int spanningTree(int V,int E,vector<vector<int> > graph);
// Driver code
int main()
{
int t;
cin>>t;
while(t--)
{
int V,E;
cin>>V>>E;
vector< vector<int> > graph(V,vector<int>(V,INT_MAX));
while(E--)
{
int u,v,w;
cin>>u>>v>>w;
u--,v--;
graph[u][v] = w;
graph[v][u] = w;
}
cout<<spanningTree(V,E,graph)<<endl;
}
return 0;
}
/*This is a function problem.You only need to complete the function given below*/
// Function to construct and print MST for
// a graph represented using adjacency
// matrix representation, with V vertices.
// graph[i][j] = weight if edge exits else INT_MAX
#include <limits.h>
int *parent;
bool *spt;
int *distance1;
int getMinVertex(int distance1[],bool spt[],int V)
{
int min_weight=INT_MAX,min_vertex=-1;
for(int i=0;i<V;i++)
{
if(!spt[i] && distance1[i]<min_weight)
min_weight=distance1[i],min_vertex=i;
}
cout<<"Min vertex : "<<min_vertex<<endl;
return min_vertex;
}
int spanningTree(int V,int E,vector<vector<int> > graph)
{
// code here
parent=new int[V];
spt=new bool[V];
distance1=new int[V];
for(int i=0;i<V;i++)
parent[i]=-1,spt[i]=false,distance1[i]=INT_MAX;
distance1[0]=0;
parent[0]=-1;
//spt[0]=true;
int current_vertex=getMinVertex(distance1,spt,V);
int mst_weight=0;
while(current_vertex!=-1)
{ cout<<"Visiting : "<<current_vertex<<endl;
for(int i=0;i<V;i++)
{
if(i!=current_vertex) //ignore self-loop
{
int neighbour_weight=graph[current_vertex][i];
if(!spt[i]&&neighbour_weight!=INT_MAX&&distance1[i]>graph[current_vertex][i])
{
distance1[i]=graph[current_vertex][i];
parent[i]=current_vertex;
}
}
}
mst_weight+=distance1[current_vertex];
spt[current_vertex]=true;
current_vertex=getMinVertex(distance1,spt,V);
cout<<"\nDistance array : \n";
for(int i=0;i<V;i++)
cout<<"dist["<<i<<"]:"<<distance1[i]<<" ";
cout<<endl;
cout<<"\nParent Array\n";
for(int i=0;i<V;i++)
cout<<"Parent["<<i<<"]:"<<parent[i]<<" ";
cout<<"\n\n";
} //end of while loop.
delete [] parent;
delete [] spt;
delete [] distance1;
//cout<<mst_weight<<endl;
return mst_weight;
}
Array spt[] consists of set of vertices already included in the set of minimum spanning tree.distance1[] array holds the distance values.Array parent[] is used to keep track of MST tree being formed.
Below is the code output for input:
2
3 2
1 2 3 1 3 3
4 3
1 3 5 1 4 6 2 3 7
Output:
Min vertex : 0
Visiting : 0
Min vertex : 2
Distance array :
dist[0]:0 dist[1]:5 dist[2]:1
Parent Array
Parent[0]:-1 Parent[1]:0 Parent[2]:0
Visiting : 2
Min vertex : 1
Distance array :
dist[0]:0 dist[1]:3 dist[2]:1
Parent Array
Parent[0]:-1 Parent[1]:2 Parent[2]:0
Visiting : 1
Min vertex : -1
Distance array :
dist[0]:0 dist[1]:3 dist[2]:1
Parent Array
Parent[0]:-1 Parent[1]:2 Parent[2]:0
4
Min vertex : 0
Visiting : 0
Min vertex : 1
Distance array :
dist[0]:0 dist[1]:5
Parent Array
Parent[0]:-1 Parent[1]:0
Visiting : 1
Min vertex : -1
Distance array :
dist[0]:0 dist[1]:5
Parent Array
Parent[0]:-1 Parent[1]:0
5
I am completely unable to make out what is going wrong with my code.Can someone please help.

Related

Time complexity analysis of UVa 539 - The Settlers of Catan

Problem link: UVa 539 - The Settlers of Catan
(UVa website occasionally becomes down. Alternatively, you can read the problem statement pdf here: UVa External 539 - The Settlers of Catan)
This problem gives a small general graph and asks to find the longest road. The longest road is defined as the longest path within the network that doesn’t use an edge twice. Nodes may be visited more than once, though.
Input Constraints:
1. Number of nodes: n (2 <= n <= 25)
2. Number of edges m (1 <= m <= 25)
3. Edges are un-directed.
4. Nodes have degrees of three or less.
5. The network is not necessarily connected.
Input is given in the format:
15 16
0 2
1 2
2 3
3 4
3 5
4 6
5 7
6 8
7 8
7 9
8 10
9 11
10 12
11 12
10 13
12 14
The first two lines gives the number of nodes n and the number of edges m for this test case respectively. The next m lines describe the m edges. Each edge is given by the numbers of the two nodes connected by it. Nodes are numbered from 0 to n - 1.
The above test can be visualized by the following picture:
Now I know that finding the longest path in a general graph is NP-hard. But as the number of nodes and edges in this problem is small and there's a degree bound of each node, a brute force solution (recursive backtracking) will be able to find the longest path in the given time limit (3.0 seconds).
My strategy to solve the problem was the following:
1. Run DFS (Depth First Search) from each node as the graph can be disconnected
2. When a node visits its neighbor, and that neighbor visits its neighbor and so on, mark the edges as used so that no edge can be used twice in the process
3. When the DFS routine starts to come back to the node from where it began, mark the edges as unused in the unrolling process
4. In each step, update the longest path length
My implementation in C++:
#include <iostream>
#include <vector>
// this function adds an edge to adjacency matrix
// we use this function to build the graph
void addEdgeToGraph(std::vector<std::vector<int>> &graph, int a, int b){
graph[a].emplace_back(b);
graph[b].emplace_back(a); // undirected graph
}
// returns true if the edge between a and b has already been used
bool isEdgeUsed(int a, int b, const std::vector<std::vector<char>> &edges){
return edges[a][b] == '1' || edges[b][a] == '1'; // undirected graph, (a,b) and (b,a) are both valid edges
}
// this function incrementally marks edges when "dfs" routine is called recursively
void markEdgeAsUsed(int a, int b, std::vector<std::vector<char>> &edges){
edges[a][b] = '1';
edges[b][a] = '1'; // order doesn't matter, the edge can be taken in any order [(a,b) or (b,a)]
}
// this function removes edge when a node has processed all its neighbors
// this lets us to reuse this edge in the future to find newer (and perhaps longer) paths
void unmarkEdge(int a, int b, std::vector<std::vector<char>> &edges){
edges[a][b] = '0';
edges[b][a] = '0';
}
int dfs(const std::vector<std::vector<int>> &graph, std::vector<std::vector<char>> &edges, int current_node, int current_length = 0){
int pathLength = -1;
for(int i = 0 ; i < graph[current_node].size() ; ++i){
int neighbor = graph[current_node][i];
if(!isEdgeUsed(current_node, neighbor, edges)){
markEdgeAsUsed(current_node, neighbor, edges);
int ret = dfs(graph, edges, neighbor, current_length + 1);
pathLength = std::max(pathLength, ret);
unmarkEdge(current_node, neighbor, edges);
}
}
return std::max(pathLength, current_length);
}
int dfsFull(const std::vector<std::vector<int>> &graph){
int longest_path = -1;
for(int node = 0 ; node < graph.size() ; ++node){
std::vector<std::vector<char>> edges(graph.size(), std::vector<char>(graph.size(), '0'));
int pathLength = dfs(graph, edges, node);
longest_path = std::max(longest_path, pathLength);
}
return longest_path;
}
int main(int argc, char const *argv[])
{
int n,m;
while(std::cin >> n >> m){
if(!n && !m) break;
std::vector<std::vector<int>> graph(n);
for(int i = 0 ; i < m ; ++i){
int a,b;
std::cin >> a >> b;
addEdgeToGraph(graph, a, b);
}
std::cout << dfsFull(graph) << '\n';
}
return 0;
}
I was ordering what is the worst case for this problem? (I'm wondering it should be n = 25 and m = 25) and in the worst case in total how many times the edges will be traversed? For example for the following test case with 3 nodes and 2 edges:
3 2
0 1
1 2
The dfs routine will be called 3 times, and each time 2 edges will be visited. So in total the edges will be visited 2 x 3 = 6 times. Is there any way to find the upper bound of total edge traversal in the worst case?

Print adjacency list

I've just started with graphs and was printing adjacency list using vector of pairs and unordered_map, though when I test my code against random custom inputs, it matches with the expected results but when I submit it to the online judge it gives me a segmentation fault.
Problem:
Given number of edges 'E' and vertices 'V' of a bidirectional graph. Your task is to build a graph through adjacency list and print the adjacency list for each vertex.
Input:
The first line of input is T denoting the number of testcases.Then first line of each of the T contains two positive integer V and E where 'V' is the number of vertex and 'E' is number of edges in graph. Next, 'E' line contains two positive numbers showing that there is an edge between these two vertex.
Output:
For each vertex, print their connected nodes in order you are pushing them inside the list .
#include<iostream>
#include<unordered_map>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--){
int nv,ne;
cin>>nv>>ne;
vector<pair<int,int>> vect;
for(int i=0;i<ne;i++)
{ int k,l;
cin>>k>>l;vect.push_back( make_pair(k,l) );
}
unordered_map<int,vector<int>> umap;
for(int i=0;i<ne;i++)
{
umap[vect[i].first].push_back(vect[i].second);
umap[vect[i].second].push_back(vect[i].first);
}
for(int i=0;i<nv;i++)
{
sort(umap[i].begin(),umap[i].end());
}
int j=0;
for(int i=0;i<nv;i++)
{
cout<<i<<"->"<<" ";
for( j=0;j<umap[i].size()-1;j++)
{
cout<<umap[i][j]<<"->"<<" ";
}
cout<<umap[i][j];
cout<<"\n";
}
}
return 0;
}
Example:
Input:
1
5 7
0 1
0 4
1 2
1 3
1 4
2 3
3 4
Output:
0-> 1-> 4
1-> 0-> 2-> 3-> 4
2-> 1-> 3
3-> 1-> 2-> 4
4-> 0-> 1-> 3
"segmentation fault" is caused when a vertex has no edges. I do not see any constraints that all vertices have at least one edge in the problem description. For example, let's consider this input.
1
3 1
0 1
Here vertex 2 does not have any edges. Let's take a look what happens in the printing loop.
for(int i=0;i<nv;i++)
{
cout<<i<<"->"<<" ";
for( j=0;j<umap[i].size()-1;j++)
{
cout<<umap[i][j]<<"->"<<" ";
}
cout<<umap[i][j];
cout<<"\n";
}
umap[i].size()-1 is dangerous : As vector<T>::size() returns an unsigned integer. So if the size is 0 then it is 0-1 and that causes underflow
Even if the first was solved (something like (int)umap[i].size()-1), the following line cout<<umap[i][j]; will try to print umap[i][0] which is invalid if the size is 0
So I would change that code like:
for(int i=0;i<nv;i++)
{
cout<<i;
for( j=0;j<umap[i].size();j++)
{
cout<<"->"<<" "<<umap[i][j];
}
cout<<"\n";
}

DFS algorithm to detect cycles in graph

#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Graph{
public:
vector<int> adjList[10001];
void addEdge(int u,int v){
adjList[u].push_back(v);
adjList[v].push_back(u);
}
};
bool dfs(Graph graph, int n){
vector<int> neighbors;
int curr,parent;
bool visited[10001] = {0};
stack<int> s;
//Depth First Search
s.push(1);
parent = 0;
while(!s.empty()){
curr = s.top();
neighbors = graph.adjList[curr];
s.pop();
//If current is unvisited
if(visited[curr] == false){
for(int j=0; j<neighbors.size(); j++){
//If node connected to itself, then cycle exists
if(neighbors[j] == curr){
return false;;
}
else if(visited[neighbors[j]] == false){
s.push(neighbors[j]);
}
//If the neighbor is already visited, and it is not a parent, then cycle is detected
else if(visited[neighbors[j]] == true && neighbors[j] != parent){
return false;
}
}
//Mark as visited
visited[curr] = true;
parent = curr;
}
}
//Checking if graph is fully connected
for(int i=1; i<=n; i++){
if(visited[i] == false){
return false;
}
}
//Only if there are no cycles, and it's fully connected, it's a tree
return true;
}
int main() {
int m,n,u,v;
cin>>n>>m;
Graph graph = Graph();
//Build the graph
for(int edge=0; edge<m; edge++){
cin>>u>>v;
graph.addEdge(u,v);
}
if(dfs(graph,n)){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
return 0;
}
I am trying to determine if a given graph is a tree.
I perform DFS and look for cycles, if a cycle is detected, then the given graph is not a tree.
Then I check if all nodes have been visited, if any node is not visited, then given graph is not a tree
The first line of input is:
n m
Then m lines follow, which represent the edges connecting two nodes
n is number of nodes
m is number of edges
example input:
3 2
1 2
2 3
This is a SPOJ question http://www.spoj.com/problems/PT07Y/ and I am getting Wrong Answer. But the DFS seems to be correct according to me.
So I checked your code against some simple test cases in comments, and it seems that for
7 6
3 1
3 2
2 4
2 5
1 6
1 7
you should get YES as answer, while your program gives NO.
This is how neighbours looks like in this case:
1: 3 6 7
2: 3 4 5
3: 1 2
4: 2
5: 2
6: 1
7: 1
So when you visit 1 you push 3,6,7 on the stack. Your parent is set as 1. This is all going good.
You pop 7 from the stack, you don't push anything on the stack and cycle check clears out, so as you exit while loop you set visited[7] as true and set you parent to 7 (!!!!!).
Here is you can see this is not going well, since once you popped 6 from the stack you have 7 saved as parent. And it should be 1. This makes cycle check fail on neighbor[0] != parent.
I'd suggest adding keeping parent in mapped array and detect cycles by applying union-merge.

Graph visit every node once and reach exit

I had a test right now and this was one of the questions:
Input
The places to visit in the labyrinth are numbered from 1 to n. The entry and
the exit correspond to number 1 and number n, respectively; the remaining
numbers correspond to crossings. Note that there are no dead ends and
there is no more than one connection linking a pair of crossings.
For each test case, the first line gives n and the number of connections
between crossings (m). Then, in each of the following m lines, you find a pair
of integers corresponding to the connection between two crossings.
Output
For each test case, your implementation should output one single line
containing "Found!", if it is possible to reach the exit by visiting every
crossing once or "Damn!", otherwise. Other test cases may follow.
Constraints
m < 32
n < 21
Example input:
8 13
1 2
1 3
2 3
2 4
3 4
3 5
4 5
4 6
5 6
5 7
6 7
6 8
7 8
8 8
1 2
1 3
2 4
3 5
4 6
5 7
6 8
7 8
Example output:
Found!
Damn!
I solved the problem using a sort of DFS algorithm but i have a few questions.
Using DFS algorithm, I implemented a recursive function that starts in the given node and tries to visit every node once and the last node must be the exit node. I don't have the full code right now but but it was something like this:
findPath(int current node, int numVisitedNodes, int *visited){
int *tmpVisited = copyArray(visited); //copies the visited array to tmpVisited
//DFS algo here
}
Every recursive call it copies the visited nodes array. I'm doing this because when it finds an invalid path and the recursion goes back to the origin, it can still go because no one overwrote the visited nodes list.
Is there any better way to do this?
How would you solve it? (you can provide code if you want)
Read the crossing
if start or end of the crossing belongs to a reachable set, add both to that set else create a new reachable set.
When input has finished, check if any of the reachable sets contains
both entrance and exit points
HashSet operations complexity is O(1). If every crossing are distinct, complexity is O(n^2),which is the worst case complexity of this algorithm. Space complexity is O(n), there is no recursion so there is no recursion overhead of memory.
Roughly speaking, every node is visited only once.
Java code using valid reachable sets is as follows.
public class ZeManel {
public static void main(String[] args) {
Integer[][] input = {{1,2},{2,3},{4,6}};
zeManel(input);
}
public static void zeManel(Integer[][] input){
List<Set<Integer>> paths = new ArrayList<Set<Integer>>();
int max = 0;
for(int i = 0;i < input.length;i++) {
max = input[i][0] > max ? input[i][0] : max;
max = input[i][1] > max ? input[i][1] : max;
boolean inPaths = false;
for (Set<Integer> set : paths) {
if(set.contains(input[i][0]) || set.contains(input[i][1])) {
set.add(input[i][0]);
set.add(input[i][1]);
inPaths = true;
break;
}
}
if(!inPaths) {
Set<Integer> path = new HashSet<Integer>();
path.add(input[i][0]);
path.add(input[i][1]);
paths.add(path);
}
}
for (Set<Integer> path : paths) {
if(path.contains(1) && path.contains(max)) {
System.out.println("Found!");
return;
}
}
System.out.println("Damn!");
}
}
This was my implementation during the test:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
# define N 21
# define M 32
int i;
int adj[N][N];
int count = 0;
int findPath(int numNodes, int currentNode, int depth, int *visited){
visited[currentNode] = 1;
if(currentNode == numNodes - 1 && depth == numNodes){
return 1;
}
if(depth > numNodes)
return -1;
int r = -1;
if(depth < numNodes){
count++;
int *tmp = (int*) malloc(numNodes*sizeof(int));
for(i = 0; i < numNodes; i++)
tmp[i] = visited[i];
for(i = 0; i < numNodes; i++){
if(adj[currentNode][i] == 1 && tmp[i] == 0 && r == -1){
if(findPath(numNodes, i, depth + 1, tmp) == 1)
r = 1;
}
}
free(tmp);
}
return r;
}
int main(){
int numLigacoes, a, b, numNodes;
int *visited;
while (scanf("%d %d", &numNodes, &numLigacoes) != EOF){
visited = (int*) malloc(numNodes*sizeof(int));
count = 0;
memset(adj, 0, N*N*sizeof(int));
memset(visited, 0, numNodes*sizeof(int));
for (i = 0; i < numLigacoes; i++){
scanf("%d %d", &a, &b);
adj[a - 1][b - 1] = 1;
adj[b - 1][a - 1] = 1;
}
if(findPath(numNodes, 0, 1, visited) == 1)
printf("Found! (%d)\n", count);
else
printf("Damn! (%d)\n", count);
free(visited);
}
return 0;
}
What do you think about that?

Go, Dijkstra : print out the path, not just calculate the shortest distance

Go, Dijkstra : print out the path, not just calculate the shortest distance.
http://play.golang.org/p/A2jnzKcbWD
I was able to find the shortest distance using Dijkstra algorithm, maybe not.
The code can be found here.
But it would be useless if I can't print out the path.
With a lot of pointers going on, I can't figure out how to print out the final path that takes the least amount of weights.
In short, how do I not only find the shortest distance, but also print out the shortest path on this given code?
The link is here:
http://play.golang.org/p/A2jnzKcbWD
And the snippet of the code is below:
const MAXWEIGHT = 1000000
type MinDistanceFromSource map[*Vertex]int
func (G *Graph) Dijks(StartSource, TargetSource *Vertex) MinDistanceFromSource {
D := make(MinDistanceFromSource)
for _, vertex := range G.VertexArray {
D[vertex] = MAXWEIGHT
}
D[StartSource] = 0
for edge := range StartSource.GetAdEdg() {
D[edge.Destination] = edge.Weight
}
CalculateD(StartSource, TargetSource, D)
return D
}
func CalculateD(StartSource, TargetSource *Vertex, D MinDistanceFromSource) {
for edge := range StartSource.GetAdEdg() {
if D[edge.Destination] > D[edge.Source]+edge.Weight {
D[edge.Destination] = D[edge.Source] + edge.Weight
} else if D[edge.Destination] < D[edge.Source]+edge.Weight {
continue
}
CalculateD(edge.Destination, TargetSource, D)
}
}
I did something with array to see what is being updated.
http://play.golang.org/p/bRXYjnIGxy
This gives ms
[A->D D->E E->F F->T B->E E->D E->F F->T]
When you adjust the new path distance here
if D[edge.Destination] > D[edge.Source]+edge.Weight {
D[edge.Destination] = D[edge.Source] + edge.Weight
Set some array element (say, P for "parent") to point that you have come to Destination from Source.
P[edge.Destination] = edge.Source
After the algorithm ends, in this array each vertex will have its predecessor on the path leading from the starting vertex.
PS. OK, not with arrays and indices ...
Add a new field Prev to the Vertex:
type Vertex struct {
Id string
Visited bool
AdjEdge []*Edge
Prev *Vertex
}
When adjusting distance:
if D[edge.Destination] > D[edge.Source]+edge.Weight {
D[edge.Destination] = D[edge.Source] + edge.Weight
edge.Destination.Prev = edge.Source
And when you display the results:
for vertex1, distance1 := range distmap1 {
fmt.Println(vertex1.Id, "=", distance1)
if vertex1.Prev != nil {
fmt.Println (vertex1.Id, " -> ", vertex1.Prev.Id)
}
}
Shortest Path-Printing using Dijkstra's Algorithm for Graph (Here it is implemented for undirected Graph. The following code prints the shortest distance from the source_node to all the other nodes in the graph.
It also prints the shortest path from the source node to the node requested by the user.
Suppose,you need to find the shortest path from A to B in the graph. Then input A as the source node and B as the destination node.
Code
#include<bits/stdc++.h>
using namespace std;
#define INF (unsigned)!((int)0)
const int MAX=2e4;
vector<pair<int,int>> graph[MAX];
bool visit[MAX];
int dist[MAX];
multiset<pair<int,int>> s;
int parent[MAX]; // used to print the path
int main(){
memset(visit,false,sizeof(visit));
memset(dist,INF,sizeof(dist));
memset(parent,-1,sizeof(parent));
int nodes,edges; cin>>nodes>>edges;
for(auto i=0;i<edges;++i){
int a,b,w;
cin>>a>>b>>w;
graph[a].push_back(make_pair(b,w));
graph[b].push_back(make_pair(a,w)); //Comment it to make the Directed Graph
}
int source_node; cin>>source_node;
dist[source_node]=0;
s.insert(make_pair(0,source_node));
while(!s.empty()){
pair<int,int> elem=*s.begin();
s.erase(s.begin());
int node=elem.second;
if(visit[node])continue;
visit[node]=true;
for(auto i=0;i<graph[node].size();++i){
int dest=graph[node][i].first;
int w=graph[node][i].second;
if(dist[node]+w<dist[dest]){
dist[dest]=dist[node]+w;
parent[dest]=node;
s.insert(make_pair(dist[dest],dest));
}
}
}
cout<<"NODE"<<" "<<"DISTANCE"<<endl;
for(auto i=1;i<=nodes;++i){
cout<<i<<" "<<dist[i]<<endl;
}
/*----PRINT SHORTEST PATH FROM THE SOURCE NODE TO THE NODE REQUESTED-------*/
int node_for_path; cin>>node_for_path;
int dest_node=node_for_path;
stack<int> path;
while(parent[node_for_path]!=source_node){
path.push(node_for_path);
node_for_path=parent[node_for_path];
}
path.push(node_for_path);
path.push(source_node);
cout<<"Shortest Path from "<<source_node<<"to "<<dest_node<<":"<<endl;
while(!path.empty()){
if(path.size()==1) cout<<path.top();
else cout<<path.top()<<"->";
path.pop();
}
return 0;
}
/*TEST CASE*/
9 14 //---NODES,EDGES---
1 2 4 //---START,END,WEIGHT---FOR THE NO OF EDGES
2 3 8
3 4 7
4 5 9
5 6 10
6 7 2
7 8 1
8 1 8
2 8 11
8 9 7
9 7 6
9 3 2
6 3 4
4 6 14
1 //---SOURCE_NODE
5 //-----NODE TO WHICH PATH IS REQUIRED
---END---*/
hope it helps

Resources