跳到正文

题解

P4408 [NOI2003] 逃学的小孩题解

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

文章信息

发布
2025年2月8日
收录
2026年7月19日
更新
2026年11月18日
篇幅
约 6 分钟
题目
P4408

版本

  1. v1当前

oioi 大佬 lsd 可是我一把屎一把尿养大的好孩子 , 从不逃学 , 但为了以防万一 , 我还是写一个程序吧 , 哎 , 这年头又有谁懂老父亲的心痛呢qwq!

首先 , 题目中明确的说 , “最坏情况下 Chris的父母要耗费多长时间才能找到 Chris?” , 让我们在这里做一个分析 , 其实,父母也想要孩子多玩会,拥有一个完好无缺的童年这不就是一个树的直径问题吗 ?

如果你连树的直径都不会,那么;

  1. 树的直径:

    • 你的代码试图通过两次 DFS 找到树的直径,但这并不是直接计算最坏情况下 Chris 的父母需要花费的时间。
    • 找到树的直径可以帮助理解树的结构,但并不直接解决题目要求的最坏情况下的时间计算。
  2. 最坏情况下的时间计算:

    • 根据题目要求,Chris 的父母会先去距离 Chris 家更近的家寻找 Chris,如果找不到,则去另一个家。
    • 需要计算从 Chris 家到 Shermie 和 Yashiro 家的距离,并根据规则确定最坏情况下的时间。

First

  1. 定义常量和变量:

    C++
    const int N=2e5+5;
    int n,m,dep[N],depp[N],ans;
    vector<pair<int,int>> v[N];
    
  • N 是最大节点数。
  • n 和 m 分别表示节点数和边数。
  • dep[N] 和 depp[N] 用于存储从某个节点出发到其他节点的距离。
  • ans 用于存储最终的答案。
  • v[N] 是一个邻接表,存储图的边信息。
  1. DFS 函数:
C++
void dfs(int u,int father)//基本模版,so easy
{
	for(auto g:v[u])//这个,是从根节点找到离它最远的点
	{
		int to=g.first,w=g.second;
		if(to==father)continue;
		dep[to]=dep[u]+w;
		dfs(to,u);
	}
}
void dfs1(int u,int father)
{
	for(auto g:v[u])//这个,是从离它最远的点到离它最远的点
	{
		int to=g.first,w=g.second;
		if(to==father)continue;
		depp[to]=depp[u]+w;
		dfs1(to,u);
	}
}
  • dfs 和 dfs1 函数用于计算从某个节点出发到其他节点的距离。
  • dfs 函数计算从根节点开始的距离。
  • dfs1 函数计算从树的直径端点之一开始的距离。
  1. 主函数:
C++
signed main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		int a,b,c;
		cin>>a>>b>>c;
		v[a].push_back({b,c});
		v[b].push_back({a,c});
	}	
	dfs(1ll,0ll);
	long long Maxx=max_element(dep+1,dep+n+1)-dep;
	dep[Maxx]=0;
	dfs(Maxx,0ll); 
	long long Maxx1=max_element(dep+1,dep+n+1)-dep;
	dfs1(Maxx1,0ll);
	for(int i=1;i<=n;i++)
	{
		if(i==Maxx||i==Maxx1) continue;
		ans=max(ans,min(dep[i],depp[i]));
	}
	cout<<ans+dep[Maxx1];
	return 0;
}
  • 读取输入的节点数 n 和边数 m。
  • 构建图的邻接表。
  • 第一次 DFS 从节点 1 开始,计算从 1 到其他节点的距离。
  • 找到距离最大的节点 Maxx,将其作为新的根节点。
  • 第二次 DFS 从 Maxx 开始,计算从 Maxx 到其他节点的距离。
  • 找到距离最大的节点 Maxx1,这是树的直径的一个端点。
  • 第三次 DFS 从 Maxx1 开始,计算从 Maxx1 到其他节点的距离。
  • 遍历所有节点,计算每个节点到 Maxx 和 Maxx1 的最小距离,并更新 ans。
  • 输出 ans + dep[Maxx1]。

代码

C++
#include<bits/stdc++.h>
#define int long long 
using namespace std;
const int N=2e5+5;
int n,m,dep[N],depp[N],ans;
vector<pair<int,int>> v[N];
void dfs(int u,int father)
{
	for(auto g:v[u])
	{
		int to=g.first,w=g.second;
		if(to==father)continue;
		dep[to]=dep[u]+w;
		dfs(to,u);
	}
}
void dfs1(int u,int father)
{
	for(auto g:v[u])
	{
		int to=g.first,w=g.second;
		if(to==father)continue;
		depp[to]=depp[u]+w;
		dfs1(to,u);
	}
}
signed main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		int a,b,c;
		cin>>a>>b>>c;
		v[a].push_back({b,c});
		v[b].push_back({a,c});
	}
	dfs(1ll,0ll);
	long long Maxx=max_element(dep+1,dep+n+1)-dep;
	dep[Maxx]=0;
	dfs(Maxx,0ll); 
	long long Maxx1=max_element(dep+1,dep+n+1)-dep;
	dfs1(Maxx1,0ll);
	for(int i=1;i<=n;i++)
	{
		if(i==Maxx||i==Maxx1) continue;
		ans=max(ans,min(dep[i],depp[i]));
	}
	cout<<ans+dep[Maxx1];
	return 0;
}
原文