diff --git a/graph/prim.cpp b/graph/prim.cpp index 5cc70bd39..0432926ef 100644 --- a/graph/prim.cpp +++ b/graph/prim.cpp @@ -3,56 +3,55 @@ #include #include -const int MAX = 1e4 + 5; -typedef std::pair PII; +using PII = std::pair; -bool marked[MAX]; -std::vector adj[MAX]; - -int prim(int x) { +int prim(int x, const std::vector< std::vector > &graph) { // priority queue to maintain edges with respect to weights std::priority_queue, std::greater > Q; - int y; - int minimumCost = 0; - PII p; + std::vector marked(graph.size(), false); + int minimum_cost = 0; Q.push(std::make_pair(0, x)); while (!Q.empty()) { // Select the edge with minimum weight - p = Q.top(); + PII p = Q.top(); Q.pop(); x = p.second; // Checking for cycle - if (marked[x] == true) + if (marked[x] == true) { continue; - minimumCost += p.first; + } + minimum_cost += p.first; marked[x] = true; - for (int i = 0; i < adj[x].size(); ++i) { - y = adj[x][i].second; - if (marked[y] == false) - Q.push(adj[x][i]); + for (const PII &neighbor : graph[x]) { + int y = neighbor.second; + if (marked[y] == false) { + Q.push(neighbor); + } } } - return minimumCost; + return minimum_cost; } int main() { - int nodes, edges, x, y; - int weight, minimumCost; - + int nodes = 0, edges = 0; std::cin >> nodes >> edges; // number of nodes & edges in graph - if (nodes == 0 || edges == 0) + if (nodes == 0 || edges == 0) { return 0; + } + + std::vector< std::vector > graph(nodes); // Edges with their nodes & weight for (int i = 0; i < edges; ++i) { + int x = 0, y = 0, weight = 0; std::cin >> x >> y >> weight; - adj[x].push_back(std::make_pair(weight, y)); - adj[y].push_back(std::make_pair(weight, x)); + graph[x].push_back(std::make_pair(weight, y)); + graph[y].push_back(std::make_pair(weight, x)); } // Selecting 1 as the starting node - minimumCost = prim(1); - std::cout << minimumCost << std::endl; + int minimum_cost = prim(1, graph); + std::cout << minimum_cost << std::endl; return 0; }