HDU 1055 Color a Tree
来源:互联网 发布:购买备案好的域名 编辑:程序博客网 时间:2024/04/28 05:39
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1055
题意:
一棵树,结点树为n,根结点为r。每个结点都有一个权值ci,开始时间为0,每染色一个结点需要耗时1,每个结点的染色代价为ci*ti(ti为当前的时间),每个结点只有在父结点已经被染色的条件下才能被染色。求染完整棵树需要花费的最小代价。
大体处理思路是利用贪心思想,每次取权值最大的节点,不断的将权值最大节点与它的父节点合并。
Sample Input
5 1
1 2 1 2 4
1 2
1 3
2 4
3 5
0 0
Sample Output
33
过程:
1、初始时将序列中的盘p[i].t都置为1,p[i].w置为p[i].c;
2、查找最大的p[i].w, 返回其位置;
3、将该位置的p[i].c与它的父节点p[i].c合并(合并过程就是C_i / T_i,C_i = c[该节点] + c[父节点],T_i = time[该节点]+time[父节点])得到新的父节点w[](w[父节点] = C_i / T_i),如果有节点与pos相连,让它指向pos的父节点;
4、重复2、3,直到合并完;
至于如何求出结果:初始时使ans = sum(p[i].c);每次查找到一个最大权值,ans += c[i] * time[父节点];(这个原因想了好久才想明白)
#include<iostream>#include<cstdio>using namespace std;int n,r;struct node{ int t,c,father; double w;}p[1005];int find()//查找最大的权值,返回其位置{ double max=0;//max必须为double,因为第一次设了int 一直wrong int pe; for(int i=1;i<=n;i++) if(p[i].w>max && i!=r)//pe不能为根节点 { max=p[i].w; pe=i; } return pe;}int main(){ while(scanf("%d %d",&n,&r) &&(n!=0 && r!=0)) { int ans=0; for(int i=1;i<=n;i++) { scanf("%d",&p[i].c); p[i].w=p[i].c;//初始p[i].w为p[i].c p[i].t=1;//初始p[i].t为1 ans=ans+p[i].c;//初始ans = sum(p[i].c) } int a,b; for(int i=1;i<n;i++) { scanf("%d %d",&a,&b); p[b].father=a;//记录父节点,建立树关系 } int j=n; while(j>1) { int pos=find();//找到最大权值的位置 p[pos].w=0;//找到后将之置0,否则影响下次查找。 int f=p[pos].father; //f为父节点 ans=ans+p[pos].c*p[f].t;//将找到的p[pos].c*p[f].t加入ans for(int i=1;i<=n;i++) if(p[i].father==pos) p[i].father=f;//如果有节点与pos相连,让它指向pos的父节点 p[f].c=p[f].c+p[pos].c;//C_i = c[该节点] + c[父节点] p[f].t=p[f].t+p[pos].t;//T_i = time[该节点]+time[父节点] p[f].w=(double)p[f].c/p[f].t;//合并后的f节点的权值 j--; } printf("%d\n",ans); }}
0 0
- hdu 1055 Color a Tree
- hdu 1055 Color a Tree
- HDU 1055 Color a Tree
- HDU 1055 color a tree
- HDU 1055 Color a Tree
- hdu 1055 Color a Tree 贪心
- hdu 1055 Color a Tree 贪心
- hdu 1055 color on a tree
- HDU 1055:Color a Tree【贪心】
- hdu 1055 Color a Tree(树上贪心,4级)
- HDU ACM 1055 Color a Tree->树上的贪心
- hdu-1055----树染色问题color a tree(贪心)
- HDU oj 1055(Color a Tree 贪心好题)
- Color a Tree
- Color a Tree
- Pku2054 Color a Tree
- poj2054 Color a Tree
- POJ2054.Color a Tree
- 不确定性原理的前世今生 · 数学篇(完)
- [jQuery]jQuery获取select文本的方法
- Android API 之Activity
- Android SDK Manager 无法下载 SDK 问题?
- POJ1163 The Triangle
- HDU 1055 Color a Tree
- android的wifi学习
- halfedge 结构
- C++程序设计-2014年11月-月末学习总结
- Android API 之 AsyncTask
- iOS开发之size Class初探
- 【性能测试思想】性能测试之系统架构分析
- 第二章——物理层
- Android API之Handler