博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
nssl1248-B【点分治,平衡树】
阅读量:2023 次
发布时间:2019-04-28

本文共 1436 字,大约阅读时间需要 4 分钟。

正题


题目大意

有一颗树,求一条路径长度k,要求 S ≤ k ≤ E S\leq k\leq E SkE,求最小的k。


解题思路

其实对于每个点进行点分治,每次将整棵子树的路径加入平衡树,然后在统计一次答案。时间复杂度 O ( n 2 ) O(n^2) O(n2)

之后我们发现其实每次就找该子树的重心继续,不用遍历整棵子树。时间复杂度 O ( 能 过 ) O(能过) O()


code

#include
#include
#include
using namespace std;const int N=100100;struct node{
int to,w,next;}a[N*3];set
ga;int siz[N],ls[N],v[N],root,S,E,n,f[N],ans,tot,x,y,w;void addl(int x,int y,int w){
a[++tot].to=y;a[tot].w=w; a[tot].next=ls[x];ls[x]=tot;}void groot(int x,int fa)//寻找重心{
siz[x]=1;f[x]=0; for(int i=ls[x];i;i=a[i].next) if(a[i].to!=fa&&!v[a[i].to]) {
groot(a[i].to,x); siz[x]+=siz[a[i].to]; f[x]=max(f[x],siz[a[i].to]); } f[x]=max(f[x],n-siz[x]); if (f[x]
=w&&w<=E) ans=min(ans,E); int maxs=*--ga.end(); if (w+maxs>=S){
int fnd=w+*ga.lower_bound(S-w); if (S<=fnd&&fnd<=E) ans=min(ans,fnd); } } for(int i=ls[x];i;i=a[i].next) if (!v[a[i].to]&&a[i].to!=fa) dfs(a[i].to,x,w+a[i].w,flag);}void dp(int x){
v[x]=1; ga.clear(); ga.insert(0); for(int i=ls[x];i;i=a[i].next) if(!v[a[i].to]) {
dfs(a[i].to,x,a[i].w,0);//根到他的路径加入平衡树 dfs(a[i].to,x,a[i].w,1);//统计答案 } for(int i=ls[x];i;i=a[i].next) if(!v[a[i].to]) {
n=siz[a[i].to]; root=0; groot(a[i].to,0);//寻找重心 dp(root);//从重心继续分治 }}int main(){
scanf("%d%d%d",&n,&S,&E); for(int i=1;i
E) ans=-1; printf("%d",ans);}

转载地址:http://nxzaf.baihongyu.com/

你可能感兴趣的文章
importlib模块与__import__详解
查看>>
python中的下划线(私有变量)
查看>>
Git的使用(2)
查看>>
tornado基础
查看>>
监控redis命令 - monitor
查看>>
tmux:终端复用神器
查看>>
elasticsearch安装与使用
查看>>
消息队列RabbitMQ
查看>>
mysql8之坑
查看>>
ImportError: No module named flask 导包失败,Python3重新安装Flask模块
查看>>
初识neo4j
查看>>
linux相关(一)
查看>>
Python 函数
查看>>
Python 基础数据类型
查看>>
pandas 数据结构与基础功能
查看>>
日期时间变量的处理
查看>>
数据框的合并排序、描述统计、分箱
查看>>
numpy库学习总结
查看>>
numpy库
查看>>
Python基础数据类型
查看>>