【BZOJ3488】[ONTAK2010]Highways
Description
给一棵n个点的树以及m条额外的双向边
q次询问,统计满足以下条件的u到v的路径:
恰经过一条额外的边
不经过树上u到v的路径上的边
Sample Input
9
1 2
2 3
4 2
1 5
5 6
7 5
7 8
9 7
4
2 5
3 4
6 4
8 3
4
4 9
2 5
1 6
1 7
1 2
2 3
4 2
1 5
5 6
7 5
7 8
9 7
4
2 5
3 4
6 4
8 3
4
4 9
2 5
1 6
1 7
Sample Output
1
4
2
2
4
2
2
题解:题意有点问题,不过你看英文就能知道,只走树边也算一条路径,所以答案先+1。
然后想到了哪道题?精神污染啊!我们只需要统计合法的非树边个数即可。具体细节呢?同精神污染,不过这里再说一遍。
如果当前询问的点为a,b,假设有一条非树边c-d,那么当且仅当满足了以下条件,c-d才对a-b产生贡献:
1.若a是b的祖先,设b在a的e儿子的子树中,那么c不在e的子树中,d在b的子树中。
2.若a不是b的祖先,则c在a的子树中,d在b的子树中。
如果用DFS序来表示上面的条件,你会发现每条非树边都相当于一个点,每次查询都相当于问1或2个矩形中点的个数,用扫描线+树状数组搞一搞就好了。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=100010;
int n,m,Q,tot,cnt;
int to[maxn<<1],next[maxn<<1],head[maxn],p1[maxn],p2[maxn],ans[maxn*5],s[maxn],dep[maxn],fa[18][maxn];
struct node
{
int x,y;
}p[maxn];
struct ask
{
int x,l,r,k,org;
ask(){}
ask(int _1,int _2,int _3,int _4,int _5) {x=_1,l=_2,r=_3,k=_4,org=_5;}
}q[maxn*15];
inline int rd()
{
int ret=0,f=1; char gc=getchar();
while(gc<'0'||gc>'9') {if(gc=='-')f=-f; gc=getchar();}
while(gc>='0'&&gc<='9') ret=ret*10+gc-'0',gc=getchar();
return ret*f;
}
inline void add(int a,int b)
{
to[cnt]=b,next[cnt]=head[a],head[a]=cnt++;
}
void dfs(int x)
{
p1[x]=++p2[0];
for(int i=head[x];i!=-1;i=next[i]) if(to[i]!=fa[0][x]) fa[0][to[i]]=x,dep[to[i]]=dep[x]+1,dfs(to[i]);
p2[x]=p2[0];
}
inline int FA(int x,int y)
{
int z=0;
while(y)
{
if(y&1) x=fa[z][x];
z++,y>>=1;
}
return x;
}
bool cmpp(const node &a,const node &b)
{
return a.x<b.x;
}
bool cmpq(const ask &a,const ask &b)
{
return a.x<b.x;
}
inline void updata(int x)
{
for(int i=x;i<=n;i+=i&-i) s[i]++;
}
inline int query(int x)
{
int i,ret=0;
for(i=x;i;i-=i&-i) ret+=s[i];
return ret;
}
int main()
{
n=rd();
int i,j,a,b,c;
memset(head,-1,sizeof(head));
for(i=1;i<n;i++) a=rd(),b=rd(),add(a,b),add(b,a);
dep[1]=1,dfs(1);
for(j=1;(1<<j)<=n;j++) for(i=1;i<=n;i++) fa[j][i]=fa[j-1][fa[j-1][i]];
m=rd();
for(i=1;i<=m;i++)
{
a=rd(),b=rd();
if(p1[a]>p1[b]) swap(a,b);
p[i].x=p1[a],p[i].y=p1[b];
}
Q=rd();
for(i=1;i<=Q;i++)
{
a=rd(),b=rd();
if(p1[a]>p1[b]) swap(a,b);
if(p2[a]>=p2[b])
{
c=FA(b,dep[b]-dep[a]-1);
q[++tot]=ask(p1[c]-1,p1[b],p2[b],1,i);
q[++tot]=ask(p1[b]-1,p2[c]+1,n,-1,i);
q[++tot]=ask(p2[b],p2[c]+1,n,1,i);
}
else
{
q[++tot]=ask(p1[a]-1,p1[b],p2[b],-1,i);
q[++tot]=ask(p2[a],p1[b],p2[b],1,i);
}
}
sort(p+1,p+m+1,cmpp);
sort(q+1,q+tot+1,cmpq);
for(i=j=1;i<=tot;i++)
{
for(;p[j].x<=q[i].x&&j<=m;j++) updata(p[j].y);
ans[q[i].org]+=(query(q[i].r)-query(q[i].l-1))*q[i].k;
}
for(i=1;i<=Q;i++) printf("%d\n",ans[i]+1);
return 0;
}//9 1 2 2 3 4 2 1 5 5 6 7 5 7 8 9 7 4 2 5 3 4 6 4 8 3 1 4 9