Gym - 102040F - Path Intersection (树链剖分)

类似 hdu3966

#include 
using namespace std;
const int maxn = 10000+10;
struct Edge
{
    int to,next;
} edge[maxn*2];
int head[maxn],tot;
int top[maxn];
int fa[maxn];
int deep[maxn];
int num[maxn];
int p[maxn];
int fp[maxn];
int son[maxn];
int pos;
void init()
{
    tot = 0;
    memset(head,-1,sizeof head);
    pos = 1;
    memset(son,-1,sizeof son);
}
void addegde(int u,int v)
{
    edge[tot].to = v;
    edge[tot].next = head[u];
    head[u] = tot++;
}
void dfs1(int u,int pre,int d)
{
    deep[u]  = d;
    fa[u] = pre;
    num[u] = 1;
    for(int i = head[u]; i != -1; i = edge[i].next)
    {
        int v = edge[i].to;
        if(v != pre)
        {
            dfs1(v,u,d+1);
            num[u] += num[v];
            if(son[u] == -1 ||num[v] > num[son[u]])
            {
                son[u] = v;
            }
        }
    }
}
void getpos(int u,int sp)
{
    top[u] = sp;
    p[u] = pos++;
    fp[p[u]] = u;
    if(son[u] == -1)
    {
        return;
    }
    getpos(son[u],sp);
    for(int i  = head[u]; i!=-1; i =edge[i].next)
    {
        int v = edge[i].to;
        if(v!= son[u]&&v != fa[u])
        {
            getpos(v,v);
        }
    }
}
int lowbit(int x)
{
    return x &(-x);
}
int c[maxn];
int n;
int sum(int i)
{
    int s = 0;
    while(i > 0)
    {
        s += c[i];
        i-= lowbit(i);
    }
    return s;
}
void add(int i,int val)
{
    while(i <= n)
    {
        c[i]+=val;
        i +=lowbit(i);
    }
}
void change(int u,int v,int val)
{
    int f1 = top[u],f2 = top[v];
    int tmp = 0;
    while(f1!=f2)
    {

        if(deep[f1] < deep[f2])
        {
            swap(f1,f2);
            swap(u,v);
        }
        add(p[f1],val);
        add(p[u]+1,-val);
        u = fa[f1];
        f1 = top[u];
    }
    if(deep[u] > deep[v])
    {
        swap(u,v);
    }

    add(p[u],val);
    add(p[v]+1,-val);
}
int main()
{
    int cas = 1;
    int M,P;
    int t;
    int u,v;
    scanf("%d",&t);
    while(t--)
    {
        init();
        scanf("%d",&n);
        M = n-1;
        while(M--)
        {
            scanf("%d%d",&u,&v);
            addegde(u,v);
            addegde(v,u);
        }
        dfs1(1,0,0);
        getpos(1,1);
        int num;
        scanf("%d",&num);
        int x;
        printf("Case %d:\n",cas++);
        int tmp;
        while(num--)
        {
            memset(c,0,sizeof c);
            scanf("%d",&x);
            tmp = x;
            while(x--)
            {
                scanf("%d%d",&u,&v);
                change(u,v,1);
            }
            int ans = 0;
            for(int i = 1; i <=n; i++)
            {
                if(sum(i) == tmp)ans++;
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}

 

你可能感兴趣的:(ACM解题记录,树状数组,树链剖分)