题解:P11251 [GESP202409 八级] 美丽路径

· · 题解

[GESP202409 八级] 美丽路径 题解

题意简述

给定一棵 n 个节点的树,每个节点有黑白两种颜色。定义美丽路径为:路径上相邻节点的颜色均不相同。求树上最长美丽路径的长度(以节点数计)。

解题思路

关键点分析

  1. 对于美丽路径的特点:

    • 相邻节点颜色必须不同
    • 是简单路径(不能经过重复节点)
    • 路径长度以节点数计算
  2. 考虑最长路径的组成方式:

    • 可能经过某个节点作为中间节点
    • 也可能以某个节点作为端点

动态规划设计

我们可以通过树形DP来解决这个问题。对于每个节点,我们需要知道:

状态定义

定义 dp[u][0/1] 表示:

状态转移

对于节点u:

  1. 如果u是白色节点:
    • 可以连接到子节点的黑色路径
    • dp[u][0] = max(dp[v][1] + 1) 其中v是u的子节点
  2. 如果u是黑色节点:
    • 可以连接到子节点的白色路径
    • dp[u][1] = max(dp[v][0] + 1) 其中v是u的子节点

答案更新

对于每个节点u,答案可能来自:

  1. 以u为端点的路径:max(dp[u][0], dp[u][1])
  2. 通过u连接两个子路径:
    • 如果u是白色:两个黑色子路径加上u
    • 如果u是黑色:两个白色子路径加上u

代码实现

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

const int MAXN = 100005;
vector<int> adj[MAXN];
int color[MAXN];
int n;
int ans = 1;  // 最小路径长度为1

// dp[i][0/1]: 以i为端点的最长路径长度,0表示路径末尾是白色,1表示路径末尾是黑色
pair<int,int> dfs(int u, int parent) {
    pair<int,int> curr = {color[u] == 0 ? 1 : 0, color[u] == 1 ? 1 : 0};
    vector<pair<int,int>> childPaths;

    for(int v : adj[u]) {
        if(v != parent) {
            childPaths.push_back(dfs(v, u));
        }
    }

    if(childPaths.empty()) return curr;

    for(auto& childPath : childPaths) {
        if(color[u] == 0) {
            curr.first = max(curr.first, childPath.second + 1);
        } else {
            curr.second = max(curr.second, childPath.first + 1);
        }
    }

    for(int i = 0; i < childPaths.size(); i++) {
        for(int j = i + 1; j < childPaths.size(); j++) {
            if(color[u] == 0) {
                ans = max(ans, childPaths[i].second + 1 + childPaths[j].second);
            } else {
                ans = max(ans, childPaths[i].first + 1 + childPaths[j].first);
            }
        }
    }

    ans = max(ans, max(curr.first, curr.second));
    return curr;
}

int main() {
    cin >> n;
    for(int i = 1; i <= n; i++) cin >> color[i];
    for(int i = 1; i < n; i++) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    dfs(1, 0);
    cout << ans << endl;
    return 0;
}

复杂度分析

注意事项

  1. 初始答案应设为1,因为单个节点也是合法路径
  2. 需要特别处理叶子节点的情况
  3. DFS时要记录父节点,避免重复访问
  4. 更新答案时需要考虑所有可能的组合方式

举例说明

对于样例1:

5
1 0 0 1 0
1 2
3 5
4 3
1 3

最长美丽路径为 2-1-3-4,长度为4。这条路径的颜色交替为:白-黑-白-黑。

小结

这是一道典型的树形DP题目,关键在于:

  1. 正确定义状态
  2. 考虑所有可能的路径组成方式
  3. 仔细处理颜色转换的限制条件

理解了这些要点,就能写出正确的解决方案。