3-22 有向树独立k中值问题
问题描述
给定一棵有向树 T,树 T 中每个顶点 u 都有一个权 w(u);树的每条边(u,v)也都有一个 非负边长 d(u,v)。有向树 T 的每个顶点 u 可以看作客户,其服务需求量为 w(u)。每条边(u,v) 的边长 d(u,v) 可以看作运输费用。如果在顶点 u 处未设置服务机构,则将顶点 u 处的服务 需求沿有向树的边(u,v)转移到顶点 v 处服务机构需付出的服务转移费用为 w(u)*d(u,v)。 树根处已设置了服务机构,现在要在树 T 中增设 k 处独立服务机构,使得整棵树 T 的服务转 移费用最小。服务机构的独立性是指任何 2 个服务机构之间都不存在有向路经。
对于给定的有向树 T,编程计算在树 T 中增设 k 处独立服务机构的最小服务转移费用。
数据输入:
第 1 行有 2 个正整数 n 和 k。n 表示有向树 T 的边数;k
是要增设的服务机构数。有向树 T 的顶点编号为 0,1,…,n。根结点编号为 0。接下来的 n 行中,每行有表示有向树 T 的一条有向边的 3 个整数。第 i+1 行的 3 个整数
分别表 示编号为 i 的顶点的权为
,相应的有向边为
,其边长为
。
Java
import java.util.Scanner;
class BiNode{
int w,wx,d,wd,dep;
int[] cost;
BiNode parent,left,right;
}
public class YouXiangShuDuLiKZhongZhi {
private static int n,k;
private static BiNode[] subt;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int a,b,c;
while (true){
n = input.nextInt();
k = input.nextInt();
subt = new BiNode[n+1];
for(int i=0; i<=n; i++)
subt[i] = new BiNode();
for(int i=1; i<=n; i++){
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
subt[i].w = a;
subt[i].wx = a;
subt[i].d = c;
BiNode p = findc(subt[b]);
BiNode q = new BiNode();
p.left = subt[i];
p.right = q;
subt[i].parent = p;
q.parent = p;
}
sd(subt[0]);
sw(subt[0]);
System.out.println(solution());
}
}
private static int solution(){
PostOrderComp(subt[0]);
return subt[0].cost[k];
}
private static void PostOrderComp(BiNode t){
if(t != null){
PostOrderComp(t.left);
PostOrderComp(t.right);
comp(t);
}
}
private static void comp(BiNode t){
if(t.left == null){
t.cost[0] = t.wd;
for(int i=1; i<=k; i++)
t.cost[i] = 0;
}else
for(int i=0; i<=k; i++) {
t.cost[i] = t.wd - t.w * t.d;
for (int a = 0; a <= i; a++) {
int tmp = t.left.cost[a] + t.right.cost[i-a] + t.wx * t.d;
if (t.cost[i] > tmp)
t.cost[i] = tmp;
}
}
}
private static void sw(BiNode t){
PostOrder(t);
}
private static void PostOrder(BiNode t){
if(t != null){
PostOrder(t.left);
PostOrder(t.right);
addw(t);
}
}
private static void addw(BiNode t){
t.wd = t.w * t.d;
if(t.left != null){
t.w += t.left.w;
t.w += t.right.w;
t.wd += t.left.wd;
t.wd += t.right.wd;
}
}
private static void sd(BiNode t){
PreOrder(t);
}
private static void PreOrder(BiNode t){
if(t != null){
adddep(t);
PreOrder(t.left);
PreOrder(t.right);
}
}
private static void adddep(BiNode t){
if(t.parent != null)
t.dep = t.parent.dep + 1;
t.cost = new int[k+1];
if(t.parent != null)
t.d += t.parent.d;
}
private static BiNode findc(BiNode q){
while (q!=null && q.right!=null)
q = q.right;
return q;
}
}
Input & Output
4 2
1 0 1
1 1 10
10 2 5
1 2 3
12
Reference
王晓东《计算机算法设计与分析》(第3版)P97