HDU5242.Game——贪心
2015-05-31 11:57
363 查看
http://acm.hdu.edu.cn/showproblem.php?pid=5242
一棵树有n个结点,n-1条边,每个结点有个权值。每次可以获得从根节点走到叶子结点所有结点的权值和,但是每个结点的权值只能使用一次。求走k次所能获得的最大权值和
dfs1求出所有结点到根节点的权值和,然后按从大到小排序,根据这个顺序,dfs2求出每个结点到根节点的权值和,遍历过的结点的权值不能用。
然后再从大到小排个序,取前面的k个
每次选择一个叶子结点走到根节点,相当于每次取一条单链,对于有交叉的两条链,先选权值大的肯定是最优的,因为对于某条跟它们没有交叉的链来说,这样子的操作并不会影响到它
一棵树有n个结点,n-1条边,每个结点有个权值。每次可以获得从根节点走到叶子结点所有结点的权值和,但是每个结点的权值只能使用一次。求走k次所能获得的最大权值和
dfs1求出所有结点到根节点的权值和,然后按从大到小排序,根据这个顺序,dfs2求出每个结点到根节点的权值和,遍历过的结点的权值不能用。
然后再从大到小排个序,取前面的k个
每次选择一个叶子结点走到根节点,相当于每次取一条单链,对于有交叉的两条链,先选权值大的肯定是最优的,因为对于某条跟它们没有交叉的链来说,这样子的操作并不会影响到它
[code]#include <bits/stdc++.h> #define clr(a,b) memset(a,b,sizeof(a)) const int maxn = 100010; using namespace std; typedef long long LL; int n,m; LL a[maxn],x[maxn]; bool vis[maxn]; struct Edge{ int to,next; }edge[maxn<<1];int head[maxn],tot; void init() { tot=0; clr(head,0xff); } void addedge(int u,int v) { edge[tot].to=v; edge[tot].next=head[u]; head[u]=tot++; } struct Node{ LL sum; int id; bool operator<(const Node&a)const{ return sum>a.sum; } }node[maxn]; LL dfs1(int u) { if(vis[u]) return node[u].sum; node[u].sum=a[u]; vis[u]=true; for(int i=head[u];~i;i=edge[i].next){ int v=edge[i].to; node[u].sum+=dfs1(v); } return node[u].sum; } LL dfs2(int u) { if(vis[u]) return 0; LL w=a[u]; vis[u]=true; for(int i=head[u];~i;i=edge[i].next){ int v=edge[i].to; w+=dfs2(v); } return w; } int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif // ONLINE_JUDGE int T,cas=1; scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); clr(node,0); for(int i=1;i<=n;++i){ scanf("%I64d",&a[i]); node[i].id=i; } clr(vis,false); init(); int u,v; for(int i=1;i<n;++i){ scanf("%d%d",&u,&v); addedge(v,u); } for(int i=1;i<=n;++i){ if(!vis[i]){ dfs1(i); } } // cout<<"-----"<<endl; sort(node+1,node+n+1); clr(vis,false); for(int i=1;i<=n;++i){ x[i]=dfs2(node[i].id); } LL ans=0; sort(x+1,x+n+1,greater<LL>()); // for(int i=1;i<=n;++i) cout<<x[i]<<" ";cout<<endl; for(int i=1,cnt=0;i<=n,cnt<m;++i) ans+=x[i],cnt++; printf("Case #%d: %I64d\n",cas++,ans); } return 0; }
相关文章推荐
- 1050 循环数组最大子段和
- (大数据之flume)Flume(NG)架构设计要点及配置实践
- 微软100题(45)几道雅虎面试题
- myeclipse 8.5 序列号
- 2015百度之星初赛(1)题解(1001)
- spark streaming测试之二使用网络数据源
- Searching: Open Addressing With Double Hashing
- Java Reflection - Dynamic Class Loading and Reloading
- Java Reflection - Arrays
- Java Reflection - Generics
- close
- (5/18)重学Standford_iOS7开发_视图控制器生命周期_课程笔记
- SQL语句之Group By&Having&where
- HDU 5246 超级赛亚ACMer(百度之星初赛第一题)
- Java Reflection - Dynamic Proxies
- Java Reflection - Annotations
- LeetCode Contains Duplicate II
- 知乎上炒的沸沸扬扬的阿里内部矛盾
- 《深入理解mybatis原理》 Mybatis初始化机制详解
- 第十三周项目一——动物这样叫