51nod 1737 配对(求贡献)
来源:互联网 发布:java生产者消费者的ppt 编辑:程序博客网 时间:2024/05/17 04:15
1737 配对
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
收藏
关注
给出一棵n个点的树,将这n个点两两配对,求所有可行的方案中配对两点间的距离的总和最大为多少。
Input
一个数n(1<=n<=100,000,n保证为偶数)接下来n-1行每行三个数x,y,z表示有一条长度为z的边连接x和y(0<=z<=1,000,000,000)
Output
一个数表示答案
Input示例
61 2 11 3 11 4 13 5 14 6 1
Output示例
7//配对方案为(1,2)(3,4)(5,6)
﹡ LH (题目提供者)
C++的运行时限为:1000 ms ,空间限制为:131072 KB 示例及语言说明请按这里
允许其他 AC 的用户查看此代码,分享代码才能查看别人的代码并有机会获得勋章
和之前写的一道树上所有任意两点的距离之和很像,都是计算每条边的贡献即可。
dfs两次,第一次求出每个点为根的子树有多少个结点。第二次求每个边的贡献
当前边的贡献一定是该边的另一个端点为根的子树大小和剩下点数量之间的最小值
也就是min(son[x],n-son[x])l;
#include<set>#include<map> #include<stack> #include<queue> #include<vector> #include<string>#include<math.h> #include<stdio.h> #include<iostream> #include<string.h> #include<stdlib.h> #include<algorithm> #include<functional> using namespace std; #define ll long long #define inf 1000000000 #define mod 1000000007 #define maxn 1000005#define lowbit(x) (x&-x) #define eps 1e-9struct node{ll x,y;};vector<node>q[maxn];ll son[maxn],ans,n;int dfs1(int u,int p){int i;son[u]=1;for(i=0;i<q[u].size();i++){node v=q[u][i];if(v.x==p)continue;son[u]+=dfs1(v.x,u);}return son[u];}void dfs2(int u,int p){int i;for(i=0;i<q[u].size();i++){node v=q[u][i];if(v.x==p)continue;ans+=min(n-son[v.x],son[v.x])*v.y;dfs2(v.x,u);}}int main(void){ll i,j,x,y,z;scanf("%lld",&n);for(i=1;i<n;i++){scanf("%lld%lld%lld",&x,&y,&z);node tmp;tmp.x=y;tmp.y=z;q[x].push_back(tmp);tmp.x=x;tmp.y=z;q[y].push_back(tmp);}dfs1(1,0);dfs2(1,0);printf("%lld\n",ans);return 0;}
阅读全文
0 0
- 51nod 1737 配对(求贡献)
- 51 nod 1737 配对(贡献)
- 51nod 1677 treecnt(逆元求组合数+求贡献)
- 51nod-1737 配对
- 【51NOD 1737】配对
- 51nod 1737 配对
- 51Nod 1737 配对
- 51Nod-1737-配对
- 51nod 1737 配对 乱搞
- 51nod 1737 配对(树的重心)
- 51nod 1737 配对【树的重心】
- 51nod 1737 配对 【树形dp】
- 51nod 1737 配对 树的重心
- 51Nod-2006-飞行员配对(二分图最大匹配)
- 51 nod 1491 黄金系统(贡献)
- 【51NOD 1558】树中的配对
- 51nod 2006 飞行员配对(二分图最大匹配) 裸匈牙利算法 求二分图最大匹配题
- 51nod 1003 阶乘后面0的数量 (5贡献的次数)
- HDU6197-array array array
- java分解质因数
- css 文字过长 点点点显示
- 做前端网页需要用网页框架吗
- Android 面试题 ANR问题总结
- 51nod 1737 配对(求贡献)
- 基于MVC+jQuery+Angularjs的Echarts的初步实现
- PAT 1130. Infix Expression (25) 前缀表达式、树的中序遍历
- log4.propertiespeiz
- android studio将多个module放在一个目录下
- 生成序列号工具类
- 快捷键总结
- tortoisegit提示pull requires the selected local branch to be the current branch
- 归并排序(O(n)辅助空间)与原地递归排序(O(1)辅助空间)