8分史山求条
查看原帖
8分史山求条
586329
Mumu_3楼主2025/1/19 18:44

改了两天还是8pts,有没有dalao帮忙看一下

orz

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

constexpr int MAXN = 100005;
constexpr int LOG_MAXN = 20; 

int n, m;
int father[MAXN][LOG_MAXN], dep[MAXN];
bool HG[MAXN]; 
vector<int> G[MAXN];

void Dfs(int p, int f) {
    dep[p] = dep[f] + 1;
    father[p][0] = f;
    for (int j = 1; j < LOG_MAXN; j++) {
        if (father[p][j-1] != -1) {
            father[p][j] = father[father[p][j-1]][j-1];
        } else {
            father[p][j] = -1; 
        }
    }
    for (int i = 0; i < G[p].size(); i++) {
        if (G[p][i] != f) Dfs(G[p][i], p);
    }
}

int LCA(int u, int v) {
    if (dep[u] < dep[v]) swap(u, v);
    for (int j = LOG_MAXN - 1; j >= 0; j--) {
        if (dep[father[u][j]] >= dep[v]) {
            u = father[u][j];
        }
    }
    if (u == v) return u;
    for (int j = LOG_MAXN - 1; j >= 0; j--) {
        if (father[u][j] != father[v][j]) {
            u = father[u][j];
            v = father[v][j];
        }
    }
    return father[u][0];
}

bool Check(int x, int y, bool cH) {
    int lca = LCA(x, y);
    bool found = false;
    if (cH) {
        for (int i = x; i != lca; i = father[i][0]) {
            if (HG[i]) found = true;
        }
        for (int i = y; i != lca; i = father[i][0]) {
            if (HG[i]) found = true;
        }
        found = found && HG[lca]; 
    } else {
        for (int i = x; i != lca; i = father[i][0]) {
            if (!HG[i]) found = true;
        }
        for (int i = y; i != lca; i = father[i][0]) {
            if (!HG[i]) found = true;
        }
        found = found || !HG[lca]; 
    }
    return found;
}

int main() {
    scanf("%d%d", &n, &m);
    getchar(); 

    for (int i = 1; i <= n; i++) {
        char c = getchar();
        HG[i] = (c == 'H');
    }

    for (int i = 1; i < n; i++) {
        int x, y;
        scanf("%d%d", &x, &y);
        G[x].push_back(y);
        G[y].push_back(x);
    }

    memset(father, -1, sizeof(father));

    Dfs(1, 0);

    string result;
    for (int i = 0; i < m; i++) {
        int x, y;
        char c;
        scanf("%d%d %c", &x, &y, &c);
        bool cH = (c == 'H');
        result += Check(x, y, cH) ? '1' : '0';
    }

    cout << result << endl;

    return 0;
}

多谢orz orz orz

2025/1/19 18:44
加载中...