跳到正文

题解

B4016

dream_NOI约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年8月7日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 5 分钟

版本

  1. v1当前

这题我用两种方法解决

1.DFS序(EASY)

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int n,cnt,head[maxn+1],maxdist,farthestNode;
struct Edge{
	int to;
	int w;
	int next;
}edge[maxn*2+1];
void add(int u,int v,int w){
	edge[cnt].w=w;
	edge[cnt].to=v;
	edge[cnt].next=head[u];
	head[u]=cnt++;
}
void init(){
	for(int i=0;i<=maxn;i++){
		head[i]=-1;
	}
}
void dfs(int u,int fa,int dist){
	if(dist>maxdist){
		maxdist=dist;
		farthestNode=u;
	}
	for(int i=head[u];i!=-1;i=edge[i].next){
		int v=edge[i].to;
		if(v==fa){
			continue;
		}
		dfs(v,u,dist+edge[i].w);
	}
}
int main(){
	init();
	cin>>n;
	for(int i=1;i<=n-1;i++){
		int x,y;
		cin>>x>>y;
		add(x,y,1);
		add(y,x,1);
	}
	dfs(1,-1,0);
	maxdist=0;
	dfs(farthestNode,-1,0);
	cout<<maxdist;
	return 0;
}

2:树形DP方法去做

C++
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAXN = 100005;  // 最大节点数
const int MAXM = 200005;  // 最大边数(树的边数为n-1,但为了安全设置为2倍)

// 链式前向星结构
struct Edge {
    int to;    // 边的终点
    int w;     // 边的权重
    int next;  // 同一起点的下一条边的索引
};

Edge edge[MAXM];  // 边集合
int head[MAXN];   // 每个节点的第一条边的索引
int cnt;          // 边的计数器

int diameter;     // 树的直径

// 初始化图
void init() {
    memset(head, -1, sizeof(head));
    cnt = 0;
    diameter = 0;
}

// 添加一条无向边
void addEdge(int u, int v, int w) {
    // 添加 u -> v 的边
    edge[cnt].to = v;
    edge[cnt].w = w;
    edge[cnt].next = head[u];
    head[u] = cnt++;
    
    // 添加 v -> u 的边(因为是无向图)
    edge[cnt].to = u;
    edge[cnt].w = w;
    edge[cnt].next = head[v];
    head[v] = cnt++;
}

// 树形DP函数,返回从节点u出发的最长路径长度
int treeDp(int u, int parent) {
    int max1 = 0;  // 最长路径
    int max2 = 0;  // 次长路径
    
    // 遍历所有邻接节点
    for (int i = head[u]; i != -1; i = edge[i].next) {
        int v = edge[i].to;
        int w = edge[i].w;
        
        // 避免回到父节点
        if (v != parent) {
            // 递归计算子节点的最长路径
            int len = treeDp(v, u) + w;
            
            // 更新最长和次长路径
            if (len > max1) {
                max2 = max1;
                max1 = len;
            } else if (len > max2) {
                max2 = len;
            }
        }
    }
    
    // 更新全局直径(经过当前节点的最长路径)
    diameter = max(diameter, max1 + max2);
    
    // 返回从当前节点出发的最长路径长度
    return max1;
}

// 寻找树的直径
int findDiameter(int n) {
    // 从节点1开始进行树形DP
    treeDp(1, -1);
    return diameter;
}

int main() {
    int n;
    cin >> n;
    
    init();
    
    for (int i = 0; i < n-1; i++) {
        int u, v;
        cin >> u >> v;
        addEdge(u, v, 1);
    }
    
    int diameter = findDiameter(n);
    cout << diameter << endl;
    
    return 0;
}
原文