File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ #include  < bits/stdc++.h> 
2+ using  namespace  std ; 
3+ #define  ll  long  long  int 
4+ #define  pb  push_back
5+ #define  mp  make_pair
6+ #define  f  first
7+ #define  s  second
8+ #define  mod  1000000007 
9+ #define  iAmInevitable  ios_base::sync_with_stdio (0 );cin.tie(0 );cout.tie(0 );
10+ // map<ll,ll> freq;
11+ // map<ll,ll> :: iterator itr;
12+ // for(itr=freq.begin();itr!=freq.end();itr++)
13+ // itr->f itr->s
14+ 
15+ const  int  MAX = 1e6 + 5 ;
16+ typedef  pair<ll, ll> PII;
17+ bool  marked[MAX];
18+ vector <PII> adj[MAX];
19+ 
20+ ll prim (int  x)
21+ {
22+  priority_queue<PII, vector<PII>, greater<PII> > Q; //  For creating minHeap
23+  ll y;
24+  ll minimumCost = 0 ;
25+  PII p;
26+  Q.push (make_pair (0 , x));
27+  while (!Q.empty ())
28+  {
29+  //  Select the edge with minimum weight
30+  p = Q.top ();
31+  Q.pop ();
32+  x = p.second ;
33+  //  Checking for cycle
34+  if (marked[x] == true )
35+  continue ;
36+  minimumCost += p.first ; // adding Edge Weight
37+  marked[x] = true ;
38+  for (ll i = 0 ;i < adj[x].size ();++i)
39+  {
40+  y = adj[x][i].second ;
41+  if (marked[y] == false )
42+  Q.push (adj[x][i]);
43+  }
44+  }
45+  return  minimumCost;
46+ }
47+ 
48+ int  main ()
49+ {
50+  int  nodes, edges, x, y;
51+  long  long  weight, minimumCost;
52+  cin >> nodes >> edges;
53+  for (int  i = 0 ;i < edges;++i)
54+  {
55+  cin >> x >> y >> weight;
56+  adj[x].push_back (make_pair (weight, y));
57+  adj[y].push_back (make_pair (weight, x));
58+  }
59+  //  Selecting 1 as the starting node
60+  minimumCost = prim (1 );
61+  cout << minimumCost << endl;
62+  return  0 ;
63+ }
64+ // This Code is Contributed by Amar Shankar
                         You can’t perform that action at this time. 
           
                  
0 commit comments