Giải thích code tìm cây bao trùm nhỏ nhất với thuật toán Prim

Em không hiểu code cho lắm có ai giúp cho e chút được ko ạ

#include<algorithm>
#include<iostream>
#include<string>
#include<queue>
#include<functional>
#include<vector>
#include<fstream>
#include <string.h>

using namespace std;

#define MAX 100

const int INF = 1e9;

vector<pair<int, int> > graph[MAX];

vector<int> dist(MAX, INF);

bool visited[MAX];

int path[MAX];

int VERTEX;

struct CompareWeight
{
	bool operator () (const pair<int, int>&vertex_1, pair<int, int>&vertex_2) const { return vertex_1.second > vertex_2.second; }

};

void Prims(int src)
{
	priority_queue<pair<int, int>, vector<pair<int, int> >,
		CompareWeight > priority_queue;
	priority_queue.push(make_pair(src, 0));
	dist[src] = 0;
	while (!priority_queue.empty())
	{
		int vertex = priority_queue.top().first;
		priority_queue.pop();
		visited[vertex] = true;
		for (int i = 0; i < graph[vertex].size(); i++)
		{
			int adjacent = graph[vertex][i].first;
			int weight = graph[vertex][i].second;
			if ( !visited[adjacent] && dist[adjacent] > weight)
			{
				dist[adjacent] = weight;
				priority_queue.push(make_pair(adjacent, weight));
				path[adjacent] = vertex;
			}
		}
	}
}



void PrintMST()
{
	int answer = 0;
	for (int i = 0; i < VERTEX; i++)
	{
		if (path[i] == -1)
			continue;

		answer += dist[i];
		cout << path[i] << " - " << i << ": " << dist[i] << endl;
	}
	cout << "Weight of MST: " << answer << endl;
}

int main()
{
	fstream FileIn;
	FileIn.open("input.txt");
	int edge, vertex, adjacent, weight;
	FileIn >> VERTEX >> edge;
	memset(path, -1, sizeof(path));
	for (int i = 0; i < edge; i++)
	{
		FileIn >> vertex >> adjacent >> weight;
		graph[vertex].push_back(make_pair(adjacent, weight));
		graph[adjacent].push_back(make_pair(vertex, weight));
	}
	FileIn.close();
	int s = 0;
	Prims(s);
	PrintMST();
	
	system("pause");
	return 0;
}

Không hiẻu chỗ nào? Đọc lại về thuật toán nhế, code chuẩn với thuật còn gì.

3 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?