树上差分-点的差分 模板

时间:2021-11-01 21:03:43
#include <bits/stdc++.h>

using namespace std;

#define INF 0x3f3f3f3f
#define MAXN 100010
#define MAXM 5010

inline int read()
{
    int x =  0,ff = 1;char ch = getchar();
    while(!isdigit(ch))
    {
        if(ch == '-') ff = -1;
        ch = getchar();
    }
    while(isdigit(ch))
    {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * ff;
}

inline void write(int x)
{
    if(x < 0) putchar('-'),x = -x;
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

int a,b,tot = 0,mx = -INF,vis[MAXN],deep[MAXN],f[MAXN][30],lin[MAXN],cnt[MAXN];  //cnt数组是点的访问次数
struct node
{
    int y,next;
}e[MAXN];

inline void add(int xx,int yy)
{
    e[++tot].y = yy;
    e[tot].next = lin[xx];
    lin[xx] = tot;
}

void BFS()
{
    queue < int > q;
    q.push(1); deep[1] = 1;
    while(!q.empty())
    {
        int x = q.front(); q.pop();
        for(int i = lin[x],y;i;i = e[i].next)
        {
            if(deep[y = e[i].y]) continue;
            deep[y] = deep[x] + 1;
            f[y][0] = x;
            for(int j = 1;(1 << j) <= a;++j)
            f[y][j] = f[f[y][j - 1]][j - 1];
            q.push(y);
        }
    }  
}

int lca(int x,int y)
{
    int t = 0;
    if(deep[x] > deep[y]) swap(x,y);
    while((1 << t) <= a) ++t;
    t--;
    for(int i = t;i >= 0;--i)
    if(deep[f[y][i]] >= deep[x]) y = f[y][i];
    if(x == y) return x;
    for(int i = t;i >= 0;--i)
    if(f[x][i] != f[y][i]) x = f[x][i],y = f[y][i];
    return f[x][0];
}

void dfs(int x)
{
    vis[x] = true;
    for(int i = lin[x],y;i;i = e[i].next)
    {
        if(vis[y = e[i].y]) continue;
        dfs(y);
        cnt[x] += cnt[y]; 
    }
}

int main()
{
    a = read(); b = read();
    for(int i = 1;i < a;++i)
    {
        int x,y;
        x = read(); y = read();
        add(x,y); add(y,x);
    }
    BFS();
    for(int i = 1;i <= b;++i)
    {
        int x,y;
        x = read(); y = read();
        int fa = lca(x,y);
        cnt[x]++; cnt[y]++;
        cnt[fa]--;
        cnt[f[fa][0]]--;
    }
    dfs(1);
    for(int i = 1;i <= a;++i)
    mx = max(mx,cnt[i]);        //该题为最大节点的访问次数
    write(mx);
    return 0;
}