跳到正文

题解

「LKJOI R1 D」和谐灯带 题解

zzrzzr114514约 6 分钟
原文
文章信息与版本

文章信息

收录
2026年1月21日
更新
2026年1月24日
篇幅
约 6 分钟

版本

  1. v1当前

题目翻译

  • 给定一棵有 nn 个节点的无根树,树上每一个节点都有一个颜色属性。颜色属性一共有三种,分别为 R,G,B。
  • 有 qq 次查询,查询节点 uu 到 vv 的路径上的节点是否存在每一种颜色且每一种颜色的节点数都不超过路径上节点数的一半。

解析

遇到树上查询类的问题,我们不难想到使用树链剖分来转换为序列上的问题。由于题目中没有修改操作,我们可以使用前缀和维护这个序列。

代码

C++
#include <bits/stdc++.h>
using namespace std;

// 结构体,方便维护信息
struct node
{
    int a,b,c;
    node():a(0),b(0),c(0){}
    node(int a,int b,int c)
        :a(a),b(b),c(c){}

    node operator+(const node& x) const
    {
        return {a+x.a,b+x.b,c+x.c};
    }
    node operator-(const node& x) const
    {
        return {a-x.a,b-x.b,c-x.c};
    }

    node& operator+=(const node& x)
    {
        a+=x.a;
        b+=x.b;
        c+=x.c;
        return *this;
    }
};

// 树剖板子部分

vector<vector<int>> gra;
vector<int> fa;
vector<int> dep;
vector<int> siz;
vector<int> son;
vector<int> top;
vector<int> dfn;
vector<node> qzh;

void dfs1(int u)
{
    dep[u]=dep[fa[u]]+1;
    for(int v:gra[u])
    {
        dfs1(v);
        siz[u]+=siz[v];
        if(siz[v]>siz[son[u]])
        {
            son[u]=v;
        }
    }
}
int tim;

void dfs2(int u,int t)
{
    dfn[u]=++tim;
    top[u]=t;
    if(son[u])
    {
        dfs2(son[u],t);
    }
    for(int v:gra[u])
    {
        if(v==son[u]) continue;
        dfs2(v,v);
    }
}

node query(int u,int v)
{
    node res;
    while(top[u]!=top[v])
    {
        if(dep[top[u]]<dep[top[v]])
        {
            swap(u,v);
        }
        res+=qzh[dfn[u]]-qzh[dfn[top[u]]-1];
        u=fa[top[u]];
    }
    if(dep[u]<dep[v]) swap(u,v);

    res+=qzh[dfn[u]]-qzh[dfn[v]-1];
    return res;
}

void read(int& x)
{
    x=0;
    int ch=getchar();
    while(!isdigit(ch)) ch=getchar();
    while(isdigit(ch))
    {
        x=x*10+(ch^48);
        ch=getchar();
    }
}

int main()
{
    int n,q;
    read(n);
    read(q);

    gra.assign(n+1,{});
    fa.assign(n+1,0);
    dep.assign(n+1,0);
    siz.assign(n+1,1);
    son.assign(n+1,0);
    top.assign(n+1,0);
    dfn.assign(n+1,0);
    qzh.assign(n+1,{});

    char s[n+1];
    scanf("%s",s);

    for(int u=2;u<=n;++u)
    {
        read(fa[u]);
        gra[fa[u]].emplace_back(u);
    }

    dfs1(1);
    dfs2(1,1);

    for(int i=0;i<n;++i)
    {
        switch(s[i])
        {
            case 'R': qzh[dfn[i+1]].a=1; break;
            case 'G': qzh[dfn[i+1]].b=1; break;
            case 'B': qzh[dfn[i+1]].c=1; break;
        }
    }
    for(int i=1;i<=n;++i)
    {
        qzh[i]+=qzh[i-1];
    }

    while(q--)
    {
        int u,v;
        read(u);
        read(v);
        node res=query(u,v);
        int mn=min({res.a,res.b,res.c});
        int mx=max({res.a,res.b,res.c});
        int sum=res.a+res.b+res.c;
        if(mx<<1>sum||mn==0)
        {
            puts("No");
        }
        else
        {
            puts("Yes");
        }
    }
}
原文