链接 : http://codeforces.com/contest/191/problem/C
思路: 直接上树剖 将每个边对应点dep 更大的点。
代码:
#include
#define lson (i<<1)
#define rson (i<<1|1)
using namespace std;
typedef long long ll;
const int N = 100005;
struct eee
{
int u,v;
int id;
int nxt;
}edge[N*2];
int head[N];
int tot;
struct node
{
int l,r;
ll sum;
ll lz;
}tr[N<<2];
int to[N];
int fat[N];
int dep[N];
int siz[N];
int son[N];
int rak[N];
int top[N];
int idd[N];
int cnt;
int n,m;
ll ans[N];
void init()
{
tot=0;
memset(head,-1,sizeof(head));
memset(son,0,sizeof(son));
memset(siz,0,sizeof(siz));
}
void add(int u,int v,int id)
{
edge[tot].u=u; edge[tot].v=v; edge[tot].nxt=head[u]; head[u]=tot;
edge[tot].id=id;
tot++;
}
void dfs1(int u,int fa,int deep)
{
fat[u]=fa;
dep[u]=deep;
siz[u]=1;
for(int i=head[u];i!=-1;i=edge[i].nxt)
{
int v=edge[i].v;
if(v==fa) continue;
dfs1(v,u,deep+1);
siz[u]+=siz[v];
if(son[u]==0||siz[v]>siz[son[u]])
{
son[u]=v;
}
}
}
void dfs2(int u,int t)
{
top[u]=t;
idd[u]=++cnt;
rak[cnt]=u;
if(!son[u]) return ;
dfs2(son[u],t);
for(int i=head[u];i!=-1;i=edge[i].nxt)
{
int v=edge[i].v;
if(v!=son[u]&&v!=fat[u])
{
dfs2(v,v);
}
}
}
void push_up(int i)
{
tr[i].sum=tr[lson].sum+tr[rson].sum;
}
void solve(int i,ll cnt,ll val)
{
tr[i].lz+=val;
tr[i].sum+=cnt*val;
}
void push_down(int i)
{
ll &lz=tr[i].lz;
if(lz!=0)
{
ll cnt=tr[lson].r-tr[lson].l+1;
solve(lson,cnt,lz);
cnt=tr[rson].r-tr[rson].l+1;
solve(rson,cnt,lz);
lz=0;
}
}
void build(int i,int l,int r)
{
tr[i].l=l; tr[i].r=r; tr[i].sum=0; tr[i].lz=0;
if(l==r) return ;
int mid=(l+r)>>1;
build(lson,l,mid);
build(rson,mid+1,r);
}
void update(int i,int l,int r,ll val)
{
if(tr[i].l==l&&tr[i].r==r)
{
//printf("*** %d %d %d\n",i,l,r);
solve(i,1ll*(r-l+1),val);
return ;
}
push_down(i);
int mid=(tr[i].l+tr[i].r)>>1;
if(r<=mid) update(lson,l,r,val);
else if(l>mid) update(rson,l,r,val);
else
{
update(lson,l,mid,val);
update(rson,mid+1,r,val);
}
push_up(i);
}
void updates(int x,int y)
{
int fx=top[x],fy=top[y];
while(fx!=fy)
{
//printf("** fx %d fy %d\n",fx,fy);
if(dep[fx]>=dep[fy])
{
// printf("********* idfx %d %d\n",idd[fx],idd[x]);
update(1,idd[fx],idd[x],1ll);
x=fat[fx];
}
else
{
// printf("********* idfy %d %d\n",idd[fy],idd[y]);
update(1,idd[fy],idd[y],1ll);
y=fat[fy];
}
fx=top[x];
fy=top[y];
}
if(x==y) return ;
if(idd[x]<=idd[y]) update(1,idd[son[x]],idd[y],1ll);
else if(idd[y]>1;
if(aim<=mid) return query(lson,aim);
else return query(rson,aim);
}
int main()
{
int u,v;
scanf("%d",&n);
init();
for(int i=1;idep[v])
{
to[u]=id;
//printf("** %d %d\n",u,id);
}
else
{
//printf("** %d %d\n",v,id);
to[v]=id;
}
}
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
scanf("%d %d",&u,&v);
updates(u,v);
}
for(int i=2;i<=n;i++)
{
int id=idd[i];
ll tmp=query(1,id);
ans[to[i]]=tmp;
}
for(int i=1;i