传送门:牛客 - 小V和gcd树
思路分析
将每个点的贡献设为他与他父亲的边权
对于修改操作,只修改其重儿子的边权
对于查询操作,先跳到顶端处,加上这个点和他父亲的边权,再跳到他的父亲
样例输入
6 5
3 6 4 9 9 9
2 1
3 2
4 2
5 4
6 5
2 4 2 2
2 1 3 5
1 3 4
2 3 6 3
2 2 3 4
样例输出
0
2
2
1
AC代码
#include <bits/stdc++.h>
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 0x3f3f3f3f;
const int N = 1e5+10;
int a[N],w[N];
vector<int>e[N];
int siz[N],son[N],fa[N],top[N],dep[N],dfn[N],cnt;
void dfs1(int u,int f){
fa[u]=f;
dep[u]=dep[f]+1;
siz[u]=1;
for(auto v:e[u]){
if(v==f) continue;
dfs1(v,u);
siz[u]+=siz[v];
if(siz[v]>siz[son[u]]) son[u]=v;
}
}
void dfs2(int u,int t){
top[u]=t;
dfn[u]=++cnt;
w[cnt]=__gcd(a[u],a[fa[u]]);
if(!son[u]) return ;
dfs2(son[u],t);
for(auto v:e[u]){
if(v==son[u]|v==fa[u]) continue;
dfs2(v,v);
}
}
int getsum(int l,int r,int k){
int ans=0;
for(int i=l;i<=r;i++) ans+=(w[i]<=k);
return ans;
}
int query(int x,int y,int k){
int ans=0;
while(top[x]!=top[y]){
if(dep[top[x]]<dep[top[y]]) swap(x,y);
ans+=getsum(dfn[top[x]]+1,dfn[x],k);
x=top[x];
ans+=(__gcd(a[x],a[fa[x]])<=k);
x=fa[x];
}
if(dep[x]>dep[y]) swap(x,y);
ans+=getsum(dfn[x]+1,dfn[y],k);
return ans;
}
int main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
int n,q;
read(n,q);
for(int i=1;i<=n;i++) read(a[i]);
for(int i=1;i<n;i++){
int u,v;
read(u,v);
e[u].pb(v);
e[v].pb(u);
}
dfs1(1,1);
dfs2(1,1);
while(q--){
int op,u,v,k;
read(op,u,v);
if(op==1){
a[u]=v;
w[dfn[u]]=__gcd(a[u],a[fa[u]]);
if(son[u]) w[dfn[son[u]]]=__gcd(a[son[u]],a[u]);
}else{
read(k);
printf("%d\n",query(u,v,k));
}
}
return 0;
}