LightOJ - 1029 Civil and Evil Engineer(最大/小生成树)
2015-11-03 23:09
513 查看
题目大意:问最小生成树和最大生成树的平均值
解题思路:模版题
解题思路:模版题
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int MAXNODE = 110; const int MAXEDGE = 12010; typedef int Type; struct Edge{ int u, v; Type d; Edge() {} Edge(int u, int v, Type d): u(u), v(v), d(d) {} }E[MAXEDGE]; int n, m, tot, cas = 1; int f[MAXNODE]; Type maxcost[MAXNODE][MAXNODE]; vector<Edge> G[MAXNODE]; //初始化并查集和最小生成树的边 void init() { scanf("%d", &n); for (int i = 0; i <= n; i++) { f[i] = i; G[i].clear(); } m = 0; while (1) { scanf("%d%d%d", &E[m].u, &E[m].v, &E[m].d); if(E[m].u == 0 && E[m].v == 0 && E[m].d == 0) break; m++; } m++; } int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); } bool cmp1(const Edge &a, const Edge &b) { return a.d < b.d; } bool cmp2(const Edge &a, const Edge &b) { return a.d > b.d; } //dfs找路径最大值,maxcost[i][j]维护的是树上的i到j点的路径上,最长的那条边的权值 void dfs(int s, int u, Type Max, int fa) { maxcost[s][u] = max(maxcost[s][u], Max); for (int i = 0; i < G[u].size(); i++) { int v = G[u][i].v; if (v == fa) continue; double tmp = max(Max, G[u][i].d); dfs(s, v, tmp, u); } } int gcd(int a, int b) { if (a % b == 0) return b; return gcd(b, a % b); } //Kruskal找到最小生成树,并将最小生成树记录下来,以便后面用来求两点之间的最长边 void solve() { sort(E, E + m, cmp1); Type Min = 0; for (int i = 0; i < m; i++) { int fx = find(E[i].u); int fy = find(E[i].v); if (fx != fy) { f[fx] = fy; Min += E[i].d; G[E[i].u].push_back(E[i]); swap(E[i].u, E[i].v); G[E[i].u].push_back(E[i]); } } for (int i = 0; i <= n; i++) f[i] = i; sort(E, E + m, cmp2); Type Max = 0; for (int i = 0; i < m; i++) { int fx = find(E[i].u); int fy = find(E[i].v); if (fx != fy) { f[fx] = fy; Max += E[i].d; G[E[i].u].push_back(E[i]); swap(E[i].u, E[i].v); G[E[i].u].push_back(E[i]); } } if ((Max + Min) % 2 == 0) printf("Case %d: %d\n", cas++, (Max + Min) / 2); else printf("Case %d: %d/2\n", cas++, Max + Min); } int main() { int test; scanf("%d", &test); while (test--) { init(); solve(); } return 0; }
相关文章推荐
- Java中try、finally语句中有return时的执行情况
- Unity3D研究院之Time.timeScale、游戏暂停(七十四)
- nodejs 入门
- 遍历指定文件夹下的所有图片,并复制到指定目录下
- !!字体图标(iconfont、Fontello 、雪碧图生成工具。Glyphicons、fontawesome 等)
- android开发笔记之配置软件版本
- 初学linux_centos7网络配置
- POJ1442
- C# 线程手册 第六章 线程调试与跟踪 跟踪开关
- 中文标点符号unicode码
- 集合元素的判断
- LightOJ - 1002 Country Roads(最小瓶颈路)
- 后盾网php网站开发培训
- 从头认识java-6.7 初始化与类的加载
- Mysql JDBC Url参数说明
- 接口
- 从头认识java-6.7 初始化与类的加载
- 字符串对齐的方法
- HDU 2647 Reward (拓扑排序)
- 生成JSON字符串