## 雯舞

Love three things int he world -- Manchery

# [点分治] HihoCoder #1462 Challenge 26 Rikka with Tree IV

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;

inline char nc(){
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}

inline void read(int &x){
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=200005;
const int K=25;

struct edge{
int u,v,next;
}G[N<<1];
int head[N],inum;

inline void add(int u,int v,int p){
G[p].u=u; G[p].v=v; G[p].next=head[u]; head[u]=p;
}

int n,iK;
#define V G[p].v
int fat[N][K],dis[N][K];
int size[N],del[N];
int sum,rt,minimum;

inline void Root(int u,int fa) {
int maximum=0;
size[u]=1;
for (int p=head[u];p;p=G[p].next)
if (V!=fa && !del[V]) {
Root(V,u);
size[u]+=size[V];
maximum=max(maximum,size[V]);
}
maximum=max(maximum,sum-size[u]);
if (minimum>maximum) minimum=maximum,rt=u;
}

int maxd;

inline void Depth(int u,int fa,int d,int f){
size[u]=1; fat[u][++*fat[u]]=f; dis[u][++*dis[u]]=d;
maxd=max(maxd,d);
for (int p=head[u];p;p=G[p].next)
if (!del[V] && V!=fa)
Depth(V,u,d+1,f),size[u]+=size[V];
}

vector<int> c1[N],c2[N];

inline void Divi(int u) {
del[u]=1;
maxd=0; Depth(u,0,0,u);
int tmp=maxd; c1[u].resize(tmp+2); c1[u][0]=tmp+1;
for (int p=head[u];p;p=G[p].next)
if (!del[V]){
sum=size[V]; minimum=1<<30;
Root(V,u);
c2[rt].resize(tmp+2); c2[rt][0]=tmp+1;
Divi(rt);
}
}

inline void Add(vector<int> &c,int x,int r){
int maxn=c[0]; x++; for (int i=x;i<=maxn;i+=i&-i) c[i]+=r;
}
inline int Query(const vector<int> &c,int x){
int ret=0; x++; x=min(x,c[0]); for (int i=x;i;i-=i&-i) ret+=c[i]; return ret;
}

inline int SQuery(int iu,int iv){
int ret=0;
for (int j=1;j<=*fat[iu];j++)
if (iv-dis[iu][j]>=0){
ret+=Query(c1[fat[iu][j]],iv-dis[iu][j]);
if (j-1) ret-=Query(c2[fat[iu][j-1]],iv-dis[iu][j]);
}
return ret;
}

inline void SAdd(int iu,int iv){
for (int j=1;j<=*fat[iu];j++){
Add(c1[fat[iu][j]],dis[iu][j],iv);
if (j-1) Add(c2[fat[iu][j-1]],dis[iu][j],iv);
}
}

int main(){
int iu,iv;
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
read(n); read(iK);
for (int i=1;i<n;i++)
read(iu),read(iv),add(iu,n+i,++inum),add(n+i,iu,++inum),add(n+i,iv,++inum),add(iv,n+i,++inum);
minimum=1<<30; sum=2*n-1; Root(1,0);
Divi(rt);
for (int i=1;i<=2*n-1;i++){
reverse(fat[i]+1,fat[i]+*fat[i]+1),reverse(dis[i]+1,dis[i]+*dis[i]+1);
if (i<=n)
SAdd(i,1);
}
int Ans=0;
if (iK&1){
for (int i=1;i<=n;i++)
Ans=max(Ans,SQuery(i,iK-1));
}else{
for (int i=n+1;i<2*n;i++)
Ans=max(Ans,SQuery(i,iK-1));
}
printf("%d\n",Ans);
return 0;
}


08-03 1027

05-13 606

07-21 552

10-10 551

03-01 1209

03-31 456

03-31 655

03-24 603

05-13 3324

04-13 852