\(kruskal\),有兴趣\(heap\_prim\)。\(stl\ pq\)实现复杂度相同。

#include <bits/stdc++.h>

using namespace std;

struct tEdge {
int a, b, c;
bool operator < (const tEdge &y) const {
return c < y.c;
}
};
tEdge edge[100005]; int fa[1005]; int father(int x) {return (fa[x] == x) ? x : (fa[x] = father(fa[x]));} bool combine(int x, int y) {
int fx = father(x), fy = father(y);
if (fx != fy) {fa[fx] = fy; return true;}
return false;
} int main() {
int n, m;
scanf("%d%d", &n, &m); for (int i = 0; i < m; ++i) scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].c); sort(edge, edge + m); for (int i = 1; i <= n; ++i) fa[i] = i; int ans = 0;
for (int i = 0, k = 0; k < n - 1; ++i)
if (combine(edge[i].a, edge[i].b) == true) {++k; ans += edge[i].c;} printf("%d", ans); return 0;
}
#include <bits/stdc++.h>

using namespace std;

int to[200005], nex[200005], w[200005], head[1005], cnt;

void addEdge(int a, int b, int c) {
to[cnt] = b; nex[cnt] = head[a]; w[cnt] = c; head[a] = cnt++;
to[cnt] = a; nex[cnt] = head[b]; w[cnt] = c; head[b] = cnt++;
} struct tNode {
int id, dis;
tNode(int i, int d) : id(i), dis(d) {}
bool operator < (const tNode &y) const {
return dis > y.dis;
}
}; int done[1005], dis[1005]; int heap_prim() {
memset(done, 0, sizeof(done));
memset(dis, 0x3f, sizeof(dis)); int ans = 0;
priority_queue<tNode> que;
dis[1] = 0;
que.push(tNode(1, 0));
while (!que.empty()) {
tNode x = que.top(); que.pop();
if (done[x.id]) continue;
ans += x.dis;
done[x.id] = 1;
dis[x.id] = 0;
for (int i = head[x.id]; i != -1; i = nex[i]) {
int l = to[i];
if (dis[l] > w[i]) {
dis[l] = w[i];
que.push(tNode(l, dis[l]));
}
}
}
return ans;
} int main() {
int n, m;
scanf("%d%d", &n, &m); memset(head, -1, sizeof(head));
cnt = 0;
for (int _ = 0, a, b, c; _ < m; ++_) {
scanf("%d%d%d", &a, &b, &c);
addEdge(a, b, c);
} printf("%d", heap_prim()); return 0;
}

最新文章

  1. sql 批量更新某个字段的值
  2. 大数据系列(2)——Hadoop集群坏境CentOS安装
  3. Hadoop里的数据挖掘应用-Mahout——学习笔记&lt;三&gt;
  4. HQL查询——select子句
  5. SQL --Chapter 04 数据更新
  6. HQL多种查询实现
  7. Android基础总结(9)——网络技术
  8. Leetcode#87 Scramble String
  9. vc6静态库的生成和调用
  10. STL源码剖析—stl_config
  11. winfrom 倒计时控件
  12. 用jQuery写了一个模态框插件
  13. phpcms 笔记
  14. github pages + Hexo + 域名绑定搭建个人博客
  15. 『练手』003 Laura.SqlForever如何扩展 兼容更多数据库引擎
  16. asp.net core 系列 14 错误处理
  17. -1-4 java io java流 常用流 分类 File类 文件 字节流 字符流 缓冲流 内存操作流 合并序列流
  18. C#--对象转Json序列化
  19. 导入项目报错【Minimum supported Gradle version is 3.3. Current version is 2.14.1】
  20. Git学习笔记02-创建版本库

热门文章

  1. bert+seq2seq 周公解梦,看AI如何解析你的梦境?【转】
  2. vue项目中使用百度统计
  3. JAVA网络通信底层调用LINUX探究
  4. day 24 组合的补充
  5. Sublime Text最好的中文教程
  6. 08-kubernetes 存储卷
  7. PHP的常用字符串处理
  8. Django4模型(操作数据库)
  9. Linux高级知识
  10. #华为云·寻找黑马程序员#【代码重构之路】如何“消除”if/else