[题解]CF1774E Two Chess Pieces

思路

正难则反,假设每一个棋子都要走过每一个点,所需的步数显然是 \(4(n - 1)\)。然后考虑对于每一个棋子那些点是必走的。

  1. 如果 \(x\) 子树内有这个棋子需要到达的点,则 \(x\) 必走。

  2. 对于另一个棋子在 \(x\) 子树内必走过的深度最深的点的深度记作 \(md\),如果 \(md - d_x > D - 1\),则 \(x\) 必走。

因此,排除掉上述点,其它点都是不用经过的,每一个点将为答案减 \(2\) 的贡献。

Code

#include <bits/stdc++.h>
#define re register

using namespace std;

const int N = 2e5 + 10,M = 4e5 + 10;
int n,k,m[2],ans;
int d[N],md[2][N];
int idx,h[N],ne[M],e[M];
bool st[2][N];

inline int read(){
    int r = 0,w = 1;
    char c = getchar();
    while (c < '0' || c > '9'){
        if (c == '-') w = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9'){
        r = (r << 3) + (r << 1) + (c ^ 48);
        c = getchar();
    }
    return r * w;
}

inline void add(int a,int b){
    ne[idx] = h[a];
    e[idx] = b;
    h[a] = idx++;
}

inline void dfs(int u,int fa){
    d[u] = d[fa] + 1;
    if (st[0][u]) md[0][u] = d[u];
    if (st[1][u]) md[1][u] = d[u];
    for (re int i = h[u];~i;i = ne[i]){
        int j = e[i];
        if (j == fa) continue;
        dfs(j,u);
        md[0][u] = max(md[0][u],md[0][j]),md[1][u] = max(md[1][u],md[1][j]);
    }
    if (!md[0][u] && md[1][u] - d[u] < k) ans -= 2;
    if (!md[1][u] && md[0][u] - d[u] < k) ans -= 2;
}

int main(){
    memset(h,-1,sizeof(h));
    n = read(),k = read();
    ans = 4 * (n - 1);
    for (re int i = 1;i < n;i++){
        int a,b;
        a = read(),b = read();
        add(a,b),add(b,a);
    }
    for (re int ty = 0;ty <= 1;ty++){
        m[ty] = read();
        for (re int i = 1;i <= m[ty];i++){
            int x;
            x = read();
            st[ty][x] = true;
        }
    }
    dfs(1,0);
    printf("%d",ans);
    return 0;
}
posted @ 2024-06-25 12:27  WBIKPS  阅读(21)  评论(0)    收藏  举报