/*==================================================*\
| 有向图最小树形图
| INIT: edge置为边表; res置为0; cp[i]置为i;
| CALL: dirtree(root, nv, ne); res是结果;
\*==================================================*/
const typec inf = 0x3f3f3f3f; // max of res
#define V 1005
#define E 1002000
int res,dis[V],N;
int to[V],cp[V],tag[V],en;
struct Edge {
int u,v,next,w;
};
Edge edge[E];
int iroot(int i){
if (cp[i] == i) return i;
return cp[i] = iroot(cp[i]);
}
bool dirtree(int root){ // root: 树根
// vertex: 0 ~ n-1
int i, j, k, circle = 0;
memset(tag, -1, sizeof(tag));
memset(to, -1, sizeof(to));
for (i = 0; i < N; ++i) dis[i] = inf;
for (j = 0; j < en; ++j) {
i = iroot(edge[j].u); k = iroot(edge[j].v);
if (k != i && dis[k] > edge[j].w) {
dis[k] = edge[j].w;
to[k] = i;
}
}
to[root] = -1; dis[root] = 0; tag[root] = root;
for (i = 0; i < N; ++i) if (cp[i] == i && -1 == tag[i]){
j = i;
for ( ; j != -1 && tag[j] == -1; j = to[j])
tag[j] = i;
if (j == -1) return 0;
if (tag[j] == i) {
circle = 1; tag[j] = -2;
for (k = to[j]; k != j; k = to[k]) tag[k] = -2;
}
}
if (circle) {
for (j = 0; j < en; ++j) {
i = iroot(edge[j].u); k = iroot(edge[j].v);
if (k != i && tag[k] == -2) edge[j].w -= dis[k];
}
for (i = 0; i < N; ++i) if (tag[i] == -2) {
res += dis[i]; tag[i] = 0;
for (j = to[i]; j != i; j = to[j]) {
res += dis[j]; cp[j] = i; tag[j] = 0;
}
}
if (0 == dirtree(root)) return 0;
} else {
for (i = 0; i < N; ++i) if (cp[i] == i) res += dis[i];
}
return 1; // 若返回0代表原图不连通
}
最小树形图
最新推荐文章于 2018-08-09 08:49:27 发布