题意:
一棵树,结点树为n,根结点为r。每个结点都有一个权值ci,开始时间为0,每染色一个结点需要耗时1,每个结点的染色代价为ci*ti(ti为当前的时间),每个结点只有在父结点已经被染色的条件下才能被染色。求染完整棵树需要花费的最小代价。
题解:
结论证明来源:poj2054-百度空间
结论1:对于一个非根结点,它具有非根结点的最大权值,那么访问完它的父亲后就要立即访问它才能使得代价最小。
处理过程:
1)建立结构体node,结构体数组e[i]表示i结点的状态,e[i].c=ci为总权值,e[i].w=ci为当前权值,e[i].t=1为经过这个结点需要的耗时(也可以理解为这个结点包含几个合并的结点),e[i].pre为父结点
2)找到一个最大权值非根结点,将其m与其父亲p合并形成一个新的结点,新结点还是原来p的位置,这个新结点的子结点为m和p的子结点;答案ans+=e[m].c*e[p].t,表示经过父节点p后,需要经历e[p].t时间才到达m,所以讲m同p合并后,总代价要加上这段路径的代价;新结点的情况e[p].c+=e[m].c,e[p].t+=e[m].t,e[p].w=1.0*e[p].c/e[p].t(新结点权值变成算术平均值,因为到这个结点的代价被平分分给t个结点)。
3)重复2)直到结点只有一个为止。
4)ans+=∑ci,因为本身染色需要耗时1,也就要支付代价ci*1.
代码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <cctype>
using namespace std;
const int maxn=1e3+10;
struct node{
int pre,c,t;
double w;//权值
}e[maxn];
int find_where(int n,int r)
{
int i,j,k,p;
double maxv=-1;
for(i=1;i<=n;i++)
{
if(i==r)continue;
if(e[i].w>maxv)
{
maxv=e[i].w;
p=i;
}
}
return p;
}
int main()
{
int n,r;
while(scanf("%d%d",&n,&r)!=EOF)
{
if(n==0&&r==0)break;
int i,j,k,a,b,m,p,ans=0;
for(i=1;i<=n;i++)
{
scanf("%d",&e[i].c);
e[i].w=e[i].c;
e[i].t=1;
ans+=e[i].c;
}
for(i=1;i<n;i++)
{
scanf("%d%d",&a,&b);
e[b].pre=a;
}
for(i=1;i<n;i++)
{
m=find_where(n,r);
e[m].w=0;
p=e[m].pre;
ans+=e[m].c*e[p].t;
for(j=1;j<=n;j++)
if(e[j].pre==m)
e[j].pre=p;
e[p].c+=e[m].c;
e[p].t+=e[m].t;
e[p].w=1.0*e[p].c/e[p].t;
}
printf("%d\n",ans);
}
return 0;
}