Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int cost[100];
- int dest[100];
- class Node
- {
- public:
- int destination;
- int weight;
- Node *next;
- };
- class Integer
- {
- public:
- Node *head = NULL;
- };
- void addEdge(Integer arr[],int sorc,int dest,int w)
- {
- Node *newNode = new Node();
- newNode->destination = dest;
- newNode->weight = w;
- newNode->next = NULL;
- if( arr[sorc].head == NULL)
- arr[sorc].head = newNode;
- else
- {
- Node *temp = arr[sorc].head;
- while(temp->next != NULL)
- temp = temp->next;
- temp->next = newNode;
- }
- }
- void display(Integer listt[], int v)
- {
- for(int i =0; i<=v; i++)
- {
- cout<<"\n Adjacency list of vertex "<<i<<" -->";
- while(listt[i].head != NULL)
- {
- cout<<" "<<listt[i].head->destination<<" "<<listt[i].head->weight;
- listt[i].head = listt[i].head->next;
- }
- }
- }
- int shortestDist(Integer adj[],int n)
- {
- cost[n] = 0;
- for (int j = n-1 ; j >=1 ; j--)
- {
- cout<<endl;
- int mini = 55555;
- int d=12;
- Node *temp = adj[j].head;
- while(temp != NULL)
- {
- int c;
- c = temp->weight+cost[temp->destination];
- if( c<mini)
- {
- mini = c;
- d = temp->destination;
- }
- temp = temp->next;
- }
- cost[j] = mini;
- cout<<j<<" "<<cost[j]<<" ";
- dest[j] = d;
- cout<<dest[j]<<endl;
- }
- return cost[1];
- }
- int main()
- {
- freopen("input.txt","r",stdin);
- int v;
- cin>>v;
- Integer arr[v];
- for (int i = 0; i <= v; i++)
- arr[i].head = NULL;
- int m,n,w;
- while(scanf("%d%d%d",&m,&n,&w) == 3)
- {
- addEdge(arr,m,n,w);
- }
- int ans =shortestDist(arr,v);
- cout<<endl<< ans<<endl;
- int temp = 1;
- cout<<1<<" ";
- for(int i=1; i<5; i++)
- {
- cout<<dest[temp]<<" ";
- temp = dest[temp];
- }
- }
- /*
- 12
- 1 2 9
- 1 3 7
- 1 4 3
- 1 5 2
- 2 6 4
- 2 7 2
- 2 8 1
- 3 6 2
- 3 7 7
- 4 8 11
- 5 7 11
- 5 8 8
- 6 9 6
- 6 10 5
- 7 9 4
- 7 10 3
- 8 10 5
- 8 11 6
- 9 12 4
- 10 12 2
- 11 12 5
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement