C++之路进阶——点分(tree)
2016-01-19 07:37
381 查看
F.A.Qs | Home | Discuss | ProblemSet | Status | Ranklist | Contest | ModifyUser gryz2016 | Logout | 捐赠本站 |
---|
1468: Tree
Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 774 Solved: 412
[Submit][Status][Discuss]
Description
给你一棵TREE,以及这棵树上边的距离.问有多少对点它们两者间的距离小于等于KInput
N(n<=40000) 接下来n-1行边描述管道,按照题目中写的输入 接下来是kOutput
一行,有多少对点之间的距离小于等于kSample Input
71 6 13
6 3 9
3 5 7
4 1 3
2 4 20
4 7 2
10
Sample Output
5HINT
题解:点分。。。
代码:
#include<iostream> #include<cstdio> #include<algorithm> #define maxn 400100 using namespace std; int n,m,root,sum,ans,cnt,head[maxn],son[maxn],f[maxn],vis[maxn],deep[maxn],d[maxn]; struct ss { int to; int next; int w; }e[maxn]; void insert(int u,int v,int w) { e[++cnt].to=v; e[cnt].next=head[u]; e[cnt].w=w; head[u]=cnt; e[++cnt].to=u; e[cnt].next=head[v]; e[cnt].w=w; head[v]=cnt; } void getroot(int x,int fa) { son[x]=1; f[x]=0; for (int i=head[x];i;i=e[i].next) if (!vis[e[i].to]&&e[i].to!=fa) { getroot(e[i].to,x); son[x]+=son[e[i].to]; f[x]=max(f[x],son[e[i].to]); } f[x]=max(f[x],sum-son[x]); if (f[x]<f[root]) root=x; } void getdeep(int x,int fa) { deep[++deep[0]]=d[x]; for (int i=head[x];i;i=e[i].next) if (!vis[e[i].to]&&e[i].to!=fa) { d[e[i].to]=d[x]+e[i].w; getdeep(e[i].to,x); } } int cal(int x,int now) { d[x]=now; deep[0]=0; getdeep(x,0); sort(deep+1,deep+deep[0]+1); int t=0,l,r; for(l=1,r=deep[0];l<r;) { if(deep[l]+deep[r]<=m){t+=r-l;l++;} else r--; } return t; } void work(int x) { ans+=cal(x,0); vis[x]=1; for (int i=head[x];i;i=e[i].next) if(!vis[e[i].to]) { ans-=cal(e[i].to,e[i].w); sum=son[e[i].to]; root=0; getroot(e[i].to,root); work(root); } } int main() { scanf("%d",&n); for (int i=1;i<n;i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); insert(u,v,w); } scanf("%d",&m); sum=n; f[0]=0x7fffffff; getroot(1,0); work(1); printf("%d",ans); }
相关文章推荐
- C语言中各种数据类型的大小
- 【C语言】冒泡排序及优化
- 移除未排序链表中的重复结点
- 用stack和面向对象的设计思想实现汉诺塔
- 详解C++编程中一元运算符的重载
- c语言中为什么左移不分符号数无符号数,而右移分呢??
- 【UE4官方文档翻译】Introduction to C++ Programming in UE4 (介绍UE4中的C++编程)
- 【OC语言】关于block的使用
- c++的坑--字符串内存拷贝注意事项
- 分别使用mingw和visual studio对cpp文件编译
- C++ Builder 静态编译设置
- c++的坑--多线程退出,单例退出
- C++制作俄罗斯方块 日志
- C++学习 【1】 C++的初步认识
- C语言之反序数组和求最大值和最小值
- C++库常用函数一览(<string><cctype><algorithm><cmath><cstdlib><iomanip><numeric>)
- C++重载和多态,
- 【c/c++】C++文件读写详解(ofstream,ifstream,fstream)
- 【C++】 引入一维数组的元素
- C++11学习笔记