【刷题】BZOJ 4543 [POI2014]Hotel加强版
Description
同OJ3522
数据范围:n<=100000
Solution
dp的设计见【刷题】BZOJ 3522 [Poi2014]Hotel
然后发现dp的第二维与深度有关,于是长链剖分就可以优化成 \(O(n)\) 的了
不会写指针,所以写deque
#include<bits/stdc++.h>
#define ui unsigned int
#define ll long long
#define db double
#define ld long double
#define ull unsigned long long
#define REP(a,b,c) for(register int a=b,a##end=c;a<=a##end;++a)
#define DEP(a,b,c) for(register int a=b,a##end=c;a>=a##end;--a)
const int MAXN=100000+10;
int n,e,to[MAXN<<1],nex[MAXN<<1],beg[MAXN],dep[MAXN],Mxdep[MAXN],hson[MAXN],top[MAXN],id[MAXN],cnt;
ll ans;
std::deque<int> f[MAXN],g[MAXN];
template<typename T> inline void read(T &x)
{
T data=0,w=1;
char ch=0;
while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
if(ch=='-')w=-1,ch=getchar();
while(ch>='0'&&ch<='9')data=((T)data<<3)+((T)data<<1)+(ch^'0'),ch=getchar();
x=data*w;
}
template<typename T> inline void write(T x,char ch='\0')
{
if(x<0)putchar('-'),x=-x;
if(x>9)write(x/10);
putchar(x%10+'0');
if(ch!='\0')putchar(ch);
}
template<typename T> inline void chkmin(T &x,T y){x=(y<x?y:x);}
template<typename T> inline void chkmax(T &x,T y){x=(y>x?y:x);}
template<typename T> inline T min(T x,T y){return x<y?x:y;}
template<typename T> inline T max(T x,T y){return x>y?x:y;}
inline void insert(int x,int y)
{
to[++e]=y;
nex[e]=beg[x];
beg[x]=e;
}
inline void dfs1(int x,int p)
{
dep[x]=dep[p]+1;Mxdep[x]=dep[x];hson[x]=x;
for(register int i=beg[x];i;i=nex[i])
if(to[i]==p)continue;
else
{
dfs1(to[i],x);
if(Mxdep[to[i]]>Mxdep[x])Mxdep[x]=Mxdep[to[i]],hson[x]=to[i];
}
}
inline void dfs2(int x,int p,int tp)
{
top[x]=tp;
if(hson[x]!=x)dfs2(hson[x],x,tp);
for(register int i=beg[x];i;i=nex[i])
if(to[i]==p||to[i]==hson[x])continue;
else dfs2(to[i],x,to[i]);
}
inline void dfs(int x,int p)
{
if(hson[x]==x)
{
id[x]=++cnt;
f[id[x]].resize(dep[x]-dep[top[x]]+1);
g[id[x]].resize(dep[x]-dep[top[x]]+1);
f[id[x]][0]=1;
return ;
}
dfs(hson[x],x);
id[x]=id[hson[x]];
f[id[x]].push_front(1);f[id[x]].pop_back();
g[id[x]].push_back(0);g[id[x]].pop_front();
ans+=g[id[x]][0];
for(register int i=beg[x];i;i=nex[i])
if(to[i]==p||to[i]==hson[x])continue;
else
{
dfs(to[i],x);
REP(j,0,Mxdep[to[i]]-dep[to[i]]+1)
{
ans+=f[id[x]][j]*g[id[to[i]]][j+1]+(j?f[id[to[i]]][j-1]*g[id[x]][j]:0);
g[id[x]][j]+=g[id[to[i]]][j+1]+(j?f[id[x]][j]*f[id[to[i]]][j-1]:0);
if(j)f[id[x]][j]+=f[id[to[i]]][j-1];
}
while(!f[id[to[i]]].empty())f[id[to[i]]].pop_back();
while(!g[id[to[i]]].empty())g[id[to[i]]].pop_back();
}
}
int main()
{
read(n);
REP(i,1,n-1)
{
int u,v;read(u);read(v);
insert(u,v);insert(v,u);
}
dfs1(1,0);dfs2(1,0,1);dfs(1,0);
write(ans,'\n');
return 0;
}