[BZOJ3757] 苹果树
嘟嘟嘟vjudge
树上莫队入门题,还没有修改。
刚做完糖果公园,顿时觉得这题水爆了。
注意有\(a = b\)的情况。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 5e4 + 5;
const int maxm = 1e5 + 5;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
const int S = 1357;
int n, m, col[maxn];
struct Edge
{
int nxt, to;
}e[maxn << 1];
int head[maxn], ecnt = -1;
void addEdge(int x, int y)
{
e[++ecnt] = (Edge){head[x], y};
head[x] = ecnt;
}
int bel[maxn], st[maxn], top = 0, cntB = 0;
int dep[maxn], fa[21][maxn];
void dfs(int now, int _f)
{
for(int i = 1; (1 << i) <= dep[now]; ++i)
fa[i][now] = fa[i - 1][fa[i - 1][now]];
int tp = top;
for(int i = head[now], v; i != -1; i = e[i].nxt)
{
if((v = e[i].to) != _f)
{
dep[v] = dep[now] + 1;
fa[0][v] = now;
dfs(v, now);
if(top - tp >= S)
{
cntB++;
while(top > tp) bel[st[top--]] = cntB;
}
}
}
st[++top] = now;
}
int lca(int x, int y)
{
if(dep[x] < dep[y]) swap(x, y);
for(int i = 20; i >= 0; --i)
if(dep[x] - (1 << i) >= dep[y]) x = fa[i][x];
if(x == y) return x;
for(int i = 20; i >= 0; --i)
if(fa[i][x] != fa[i][y]) x = fa[i][x], y = fa[i][y];
return fa[0][x];
}
struct Node
{
int x, y, id, a, b;
bool operator < (const Node& oth)const
{
if(bel[x] != bel[oth.x]) return bel[x] < bel[oth.x];
if(bel[y] != bel[oth.y]) return bel[y] < bel[oth.y];
return id < oth.id;
}
}q[maxm];
bool vis[maxn];
int tot[maxn], ans[maxm], cnt = 0;
void Rev(int now)
{
if(vis[now])
{
if(!--tot[col[now]]) cnt--;
}
else if(!tot[col[now]]++) cnt++;
vis[now] ^= 1;
}
void move(int x, int y)
{
int z = lca(x, y);
while(x != z) Rev(x), x = fa[0][x];
while(y != z) Rev(y), y = fa[0][y];
}
int main()
{
Mem(head, -1);
n = read(); m = read();
for(int i = 1; i <= n; ++i) col[i] = read();
for(int i = 1; i <= n; ++i)
{
int x = read(), y = read();
addEdge(x, y); addEdge(y, x);
}
dfs(1, 0);
while(top) bel[st[top--]] = cntB;
for(int i = 1; i <= m; ++i)
q[i].id = i, q[i].x = read(), q[i].y = read(), q[i].a = read(), q[i].b = read();
sort(q + 1, q + m + 1);
int px = 1, py = 1;
for(int i = 1; i <= m; ++i)
{
move(px, q[i].x), px = q[i].x;
move(py, q[i].y), py = q[i].y;
Rev(lca(px, py));
ans[q[i].id] = cnt;
if(tot[q[i].a] && tot[q[i].b] && q[i].a != q[i].b) ans[q[i].id]--;
Rev(lca(px, py));
}
for(int i = 1; i <= m; ++i) write(ans[i]), enter;
return 0;
}