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 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 input()
- {
- cin>>vertex>>edge;
- for(int i=1; i<=edge;i++)
- {
- cin>>u>>v>>weight;
- adj[u][v] = weight;
- adj[v][u] = weight;
- }
- }
- void solution()
- {
- priority_queue<Node>pq;
- pq.push(Node(0,0));
- int parent[100]={0};
- while(!pq.empty())
- {
- Node temp = pq.top();
- pq.pop();
- if(visited[temp.v] == 1) continue;
- cout<<parent[temp.v]<<" "<<temp.v<<" "<<temp.cost<<endl;
- //parent = temp.v;
- ans +=temp.cost;
- visited[temp.v] =1;
- for(i = 0;i<vertex;i++)
- {
- /// for loop not create
- if(visited[i] == 1)
- {
- continue;
- }
- /// skip some vertex that are not adjacent
- if(adj[temp.v][i] !=0)
- {
- pq.push(Node(i,adj[temp.v][i]));
- parent[i]= temp.v;
- //cout<<i<<" "<<adj[temp.v][i]<<endl;
- }
- }
- }
- cout<<endl<<"Minimum cost is "<<ans<<endl;
- }
- };
- int main()
- {
- freopen("input.txt","r",stdin);
- Prims p;
- p.input();
- p.solution();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement