您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: