Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- ifstream file;
- ofstream file2;
- int findMin(int* distance,bool* visited,int n)
- {
- int minVertex = -1;
- for(int i = 0 ; i<n; i++)
- {
- if(!visited[i] && (minVertex==-1 || distance[i]<distance[minVertex]))
- {
- minVertex = i;
- }
- }
- return minVertex;
- }
- void printPath(int *parent, int destination)
- {
- if (parent[destination] == - 1)
- return;
- printPath(parent, parent[destination]);
- file2<<"->"<<destination;
- }
- void dijkstra(int** graph,int n,int source,int destination)
- {
- bool* visited = new bool[n];
- int *distance = new int[n];
- int *parent = new int[n];
- for(int i =0; i<n; i++)
- {
- distance[i] = INT_MAX;
- visited[i] = false;
- parent[i] = -1;
- }
- distance[source] = 0;
- for(int i =0; i<n; i++)
- {
- int minVertex = findMin(distance,visited,n);
- visited[minVertex] = true;
- for(int j = 0; j<n; j++)
- {
- if(graph[minVertex][j]!=0 && !visited[j])
- {
- int dist = distance[minVertex] + graph[minVertex][j];
- if(dist<distance[j])
- {
- distance[j] = dist;
- parent[j] = minVertex;
- }
- }
- }
- }
- file2<<distance[destination]<<endl;
- file2<<source;
- printPath(parent,destination);
- }
- void bellman(int** graph,int n,int m,int source,int destination)
- {
- int *distance = new int[n];
- int *parent = new int[n];
- for(int i =0; i<n; i++)
- {
- distance[i] = INT_MAX;
- parent[i] = -1;
- }
- distance[source] = 0;
- for(int i = 0; i<n-1; i++)
- {
- for(int j = 0; j<m; j++)
- {
- int u = graph[j][0];
- int v = graph[j][1];
- int w = graph[j][2];
- if (distance[u]!=INT_MAX && distance[u] + w < distance[v])
- {
- distance[v] =distance[u] + w;
- parent[v] = u;
- }
- }
- }
- for(int i =0; i<m; i++)
- {
- int u = graph[i][0];
- int v = graph[i][1];
- int w = graph[i][2];
- if(distance[u]!=INT_MAX && distance[u]+w <distance[v])
- {
- file2<<"Graph contains Negative weight cycle"<<endl;
- }
- }
- file2<<distance[destination]<<endl;
- file2<<source;
- printPath(parent,destination);
- }
- int main()
- {
- file.open("test.txt");
- int n,m,s,d;
- file>>n>>m;
- int **matrix = new int*[n];
- int **graph = new int*[n];
- for(int i = 0; i < n; i++)
- {
- matrix[i] = new int[n];
- for(int j = 0; j < n; j++)
- {
- matrix[i][j] = 0;
- }
- }
- for(int i = 0; i<m; i++)
- {
- graph[i] = new int[3];
- int u,v,w;
- file>>u>>v>>w;
- matrix[u][v] = abs(w);
- graph[i][0] = u;
- graph[i][1] = v;
- graph[i][2] = w;
- }
- file>>s>>d;
- file.close();
- file2.open("1705111.txt");
- file2<<"Bellman Ford Algorithm:"<<endl;
- bellman(graph,n,m,s,d);
- file2<<"\n\n";
- file2<<"Dijkstra Algorithm:"<<endl;
- dijkstra(matrix,n,s,d);
- file2.close();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement