prim 堆优化

本文详细介绍了如何对经典的Prim最小生成树算法进行堆优化,通过优化提高算法效率,降低时间复杂度,适合对图论和算法优化感兴趣的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <queue>
using namespace std;
const int MAXN = 1005;
const int INF = 1 << 30;

struct Node {
	int u, w;
	friend bool operator<(const Node& a, const Node& b)
	{
		return a.w > b.w;
	}
	Node() {}
	Node(int uu, int ww) : u(uu), w(ww) {}
};

vector<Node> graph[MAXN];

int prim(int n)
{
	
	bool vis[MAXN]{ false };
	priority_queue<Node> q;
	vis[1] = true;
	
	for (int i = 0; i < graph[1].size(); ++i)
		q.push(graph[1][i]);
	int ans = 0;
	int cnt = 0;
	Node t;
	while (cnt < n - 1)
	{
		t = q.top();
		q.pop();
		if (vis[t.u])
			continue;
		vis[t.u] = true;
		ans += t.w;
		++cnt;
		int n = t.u;
		for (int i = 0; i < graph[n].size(); ++i)
			if (!vis[graph[n][i].u])
				q.push(graph[n][i]);
	}
	return ans;
}


int main(void)
{
	int n, m, u, v, w;
	scanf("%d%d", &n, &m);
	while (m--)
	{
		scanf("%d %d %d", &u, &v, &w);
		graph[u].push_back(Node(v, w));
		graph[v].push_back(Node(u, w));
	}
	cout << prim(n) << endl;
	return 0;
}

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值