题解:CF463E Caisa and Tree

· · 题解

首先,我们注意到较为难搞的修改操作最多只有 50 次,那么我们就可以考虑预处理答案加上暴力修改。

查询操作

先预处理答案。

由于要求的是 x 的最近祖先 v 使得 \gcd(a_x,a_y)>1,即使得 a_u 和 a_v 存在大于 1 的公因子,故我们考虑维护出每一个点的所有因子。维护完成后,就可以遍历整棵树进而求出答案了。具体地,我们可以对每个因子都开一个类似于栈的东西,对于遍历到的每个点,该点的答案就是所有它的因子所对应的所有栈的栈底的深度的最大值的那个点(因为要求的是最近祖先,所以是栈底),之后将它放进它每个因子对应的栈里面。

这样答案就求好了。对于每个询问,只要输出我们预处理的答案就可以啦。

修改操作

由于对点 u 进行修改只有 u 及其子树的答案会受到影响,所以只需要递归 u 的子树就行。因为修改操作最多只有 50 次,所以我们的时间复杂度是非常正确的。

那么这道题的思路就大致差不多啦,具体实现见代码。

#include <bits/stdc++.h>
#define re register
using namespace std;
inline int read()
{
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0' && ch<='9')
        x=x*10+ch-'0',ch=getchar();
    return x*f;
}
void write(int x)
{
    if(x<0)
        putchar('-'),x=-x;
    if(x>9)
        write(x/10);
    putchar(x%10+'0');
    return;
}
int n,q;
const int N = 1e5 + 10,M = 2e6 + 10;;
int a[N];
vector <int> g[N];


vector <int> zyz[N];
void get(int qwq){
    zyz[qwq].clear(); 
    int x = a[qwq];
    for(re int i = 2;i * i <= x;i ++){
        if(x % i == 0){
            zyz[qwq].push_back(i);
            while(x % i == 0) x /= i;
        }
    }
    if(x>1) zyz[qwq].push_back(x);
    return;
}


int ans[N];
vector <int> st[M];
int dep[N],fa[N];
void dfs(int u,int father) {
    ans[u] = -1;//因为要求没有输出-1 所以默认先设为-1
    dep[u] = dep[father] + 1;//节点深度 便于求答案
    fa[u] = father; 
    for (auto v : zyz[u]){
        if(!st[v].empty() && (ans[u] == -1 || dep[ans[u]] < dep[st[v].back()])){
        ans[u] = st[v].back();//这段就是如果前面有和点u有相同因子的那答案就取深度最深的
    } 
        st[v].push_back(u); 
    }
    for (auto v : g[u]){
        if(v == father) continue;
        dfs(v,u);
    } 
    for (auto v : zyz[u]){
        st[v].pop_back();//清除u的因子 以免对其他子树答案处理时产生影响 
    }
    return;
}
vector <int> die;
int main(){
    n = read();
    q = read();
    for (re int i = 1;i <= n;i ++) {a[i] = read();get(i);} //对于每个点求出它的因子
    for (re int i = 1;i < n;i ++){
        int u = read(),v = read();
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(1,0); //预处理部分啦
    while(q --){
        int opt = read();
        if(opt == 1) {
            int x = read(); 
            write(ans[x]);//输出预处理好的答案就行啦
            puts(""); 
        }else{
            int ovo1 = read();
            int ovo = ovo1;
            int qwq = read();
            while(ovo) {
                ovo = fa[ovo];
                die.push_back(ovo);//把点x的所有祖先都存起来,因为有可能x与其子树的答案在它的祖先节点上
            } 
            reverse(die.begin(),die.end()); 
            for (auto pwp : die){
                for(auto v : zyz[pwp]) st[v].push_back(pwp); //把祖先节点也加进因子栈里
            }
            a[ovo1] = qwq;//更新x的值
            get(ovo1); 
            dfs(ovo1,fa[ovo1]);//递归以x为根的子树
            for (auto pwp : die){

                for(auto v : zyz[pwp]) st[v].pop_back();//清除x祖先节点的因子 以免影响到其他的修改操作 
            } 
            die.clear();
        }
    }
    return 0;
}