Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int adj[1000][1000];
- 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 = listt[i].head->next;
- }
- }
- }
- class node{
- public:
- int v,cost;
- node()
- {
- }
- node(int vertex,int costt)
- {
- v= vertex;
- cost = costt;
- }
- };
- bool operator<(node a,node b)
- {
- return a.cost>b.cost;
- }
- class Prims{
- int vertex,edge,u,v,weight,i,j,ans = 0;
- bool visited[100] = {false};
- public:
- void solution(Integer adj[],int v)
- {
- priority_queue<node>pq;
- pq.push(node(0,0));
- //int parent[100]={0};
- while(!pq.empty())
- {
- //cout<<"hi";
- node temp = pq.top();
- pq.pop();
- if(visited[temp.v] == 1) continue;
- cout<<temp.v<<" "<<temp.cost<<endl;
- //parent = temp.v;
- ans +=temp.cost;
- visited[temp.v] =1;
- Node *tmp = adj[temp.v].head;
- while(tmp != NULL)
- {
- //cout<<"hello"<<endl;
- if(visited[tmp->destination] == 1)
- {
- tmp = tmp->next;
- continue;
- }
- pq.push(node(tmp->destination,tmp->weight));
- tmp = tmp->next;
- }
- }
- cout<<endl<<"Minimum cost is "<<ans<<endl;
- }
- };
- int main()
- {
- freopen("input.txt","r",stdin);
- int v,E;
- cin>>v>>E;
- Integer arr[v];
- /// eita na korle arr er vitore v+1 dite hobe
- for (int i = 0; i <= v; i++)
- arr[i].head = NULL;
- /// getting input
- int m,n,w;
- while(scanf("%d%d%d",&m,&n,&w) == 3)
- {
- addEdge(arr,m,n,w);
- addEdge(arr,n,m,w);
- }
- //display(arr,v);
- Prims p;
- p.solution(arr,v);
- }
- /*
- 5 7
- 0 1 6
- 0 2 1
- 1 2 2
- 2 3 8
- 1 3 3
- 1 4 1
- 3 4 6
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement