零食采购\\
作者:
制度外
,
2024-06-08 20:50:38
,
所有人可见
,
阅读 11
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PII;
const ll N = 1e5 + 10;
PII dp[N][30];
ll depth[N];
ll c[N];//零食
struct node{
vector<ll> childs;
}a[N];
ll n,m;
void dfs(ll i,ll fi){
depth[i]=depth[fi]+1;
dp[i][0]=(PII){fi,(1<<c[i])|(1<<c[fi])};
for (ll j = 1;j <= 24;j ++){
PII k1 = dp[i][j-1];
PII k2 = dp[k1.first][j-1];
dp[i][j] = (PII){k2.first,k1.second | k2.second};
}
for (auto t : a[i].childs){
if (t == fi) continue;
dfs(t,i);
}
}
ll lca(ll x,ll y){
if (depth[x] < depth[y]) swap(x,y);
ll ans = (1<<c[x])|(1<<c[y]);
for (ll i = 24;i >= 0;i --){
PII k1 = dp[x][i];
if (depth[k1.first] < depth[y]) continue;
x = k1.first;
ans |= k1.second;
}
if (x == y) return ans;
for (ll i = 24;i >= 0;i --){
PII k1 = dp[x][i];
PII k2 = dp[y][i];
if (k1.first == k2.first) continue;
x = k1.first;
y = k2.first;
ans |= k1.second;
ans |= k2.second;
}
ans |= dp[x][0].second;
ans |= dp[y][0].second;
return ans;
}
ll lowbit(ll x){
return x&-x;
}
int main(){
cin >> n >> m;
for (ll i = 1;i <= n;i ++){
cin >> c[i];
c[i] --;
}
for (ll i = 1;i < n;i ++){
ll x,y;cin >> x >> y;
a[x].childs.push_back(y);
a[y].childs.push_back(x);
}
c[0] = c[1];
dfs(1,0);
while (m --){
ll x,y;cin >> x >> y;
ll t = lca(x,y);
ll ans = 0;
for (int i = 0;i <= 19;i ++){
if (t & (1<<i))
ans ++;
}
cout << ans << endl;
}
return 0;
}
麻烦你了