树的直径 两次bfs

树的直径

定义 : 树中所有最短路径的最大值即为树的直径

性质 :

性质A: 设任意一点 U U U的最远的节点为 V V V,则 V V V一定是直径某个端点

性质B: 树的所有直径有一个公共交点
(这是某个大佬的博客的截图,太久了不知道原链接在哪里了)

求法 :

  • 两次 b f s bfs bfs (无法求负边权的树直径)
    • 任选一个点 S S S开始bfs到它的最远距离 V V V
    • 再从 V V V开始 b f s bfs bfs到距离 V V V的最远点 U U U
    • U , V U,V U,V就是直径两端点
  • 树型 D P DP DP (不会)

例题:

  • 求树上所有点的最远点hdu2196

模板

  • 两次bfs求树直茎

    struct Node {
    	int v, step;
    } ;
    struct Edge {
    	int to, w;
    } ;
    vector<Edge> G[MAXN];
    int bfs(int S) { //bfs返回距离起点S最远的点
    	queue<Node> q;
    	memset(vis, false, sizeof(vis));
    	q.push({ S, 0 });
    	vis[S] = true;
    	int tstep = 0/*当前最远距离*/, ret = S;
    	while(!q.empty()) {
    		auto no = q.front(); q.pop();
    		int u = no.v;
    		if(no.step > tstep) {
    			tstep = no.step;
    			ret = u;
    		}
    		for(auto ed : G[u]) {
    			int v = ed.to, w = ed.w;
    			if(!vis[v]) 
                  q.push({v, no.step+w}),
              	  vis[v] = true;
    		}
    	}
    	return ret;
    }
    
hdu2196

给定一颗树,打印树上每个点的最远点代码

  • 利用性质 A A A : 先求直径两端点 U , V U,V U,V,
  • U U U点开始 d f s dfs dfs求每个点到 U U U的距离
  • 再从 V V V点开始 d f s dfs dfs更新最大距离

完整代码

#define debug
#ifdef debug
#include <time.h>
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>

#define MAXN ((int)1e4+7)
#define ll long long 
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;

#define show(x...) \ do { \ cout << "\033[31;1m " << #x << " -> "; \ err(x); \ } while (0)

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO {

	char print_f[105];
	void read() { }
	void print() { putchar('\n'); }

	template <typename T, typename... T2>
		inline void read(T &x, T2 &... oth) {
			x = 0;
			char ch = getchar();
			ll f = 1;
			while (!isdigit(ch)) {
				if (ch == '-') f *= -1; 
				ch = getchar();
			}
			while (isdigit(ch)) {
				x = x * 10 + ch - 48;
				ch = getchar();
			}
			x *= f;
			read(oth...);
		}
	template <typename T, typename... T2>
		inline void print(T x, T2... oth) {
			ll p3=-1;
			if(x<0) putchar('-'), x=-x;
			do{
				 print_f[++p3] = x%10 + 48;
			} while(x/=10);
			while(p3>=0) putchar(print_f[p3--]);
			putchar(' ');
			print(oth...);
		}
} // namespace FastIO
using FastIO::print;
using FastIO::read;

int n, m, Q, K, U, V, ans[MAXN];
bool vis[MAXN];

struct Node {
	int v, step;
} ;

struct Edge {
	int to, w;
} ;
vector<Edge> G[MAXN];

void init() {
	for(int i=1; i<=n+1; i++) 
		G[i].clear(), vis[i] = false, ans[i] = 0;
}

int bfs(int S) { //bfs返回距离起点S最远的点
	queue<Node> q;
	memset(vis, false, sizeof(vis));
	q.push({ S, 0 });
	vis[S] = true;
	int tstep = 0/*当前最远距离*/, ret = S;
	while(!q.empty()) {
		auto no = q.front(); q.pop();
		int u = no.v;
		if(no.step > tstep) {
			tstep = no.step;
			ret = u;
		}
		for(auto ed : G[u]) {
			int v = ed.to, w = ed.w;
			if(!vis[v]) q.push({v, no.step+w}), vis[v] = true;
		}
	}
	return ret;
}

void dfs(int u, int fa, int level) {
	ans[u] = max(ans[u], level); //更新u到直径两端的最远距离
	for(auto ed : G[u]) {
		int v = ed.to, w = ed.w;
		if(fa != v) dfs(v, u, level+w);
	}
}

signed main() {
#ifdef debug
	freopen("test", "r", stdin);
	clock_t stime = clock();
#endif
	while(~scanf("%d ", &n)) {
		init();
		int u, v, w;
		for(int i=2; i<=n; i++) {
			u = i;
			scanf("%d %d ", &v, &w);
			G[u].push_back({v, w}), G[v].push_back({u, w});
		}
#if 0
		for(int i=1; i<=n; i++) {
			printf("%d : ", i);
			for(auto ed : G[i])
				printf("->%d", ed.to);
			printf("\n");
		}
#endif
		u = bfs(v); //两次bfs求出树的直径
		v = bfs(u);
		U = u, V = v; //树的直径分别为
// show(U, V);
		vis[U] = true;
		dfs(U, -1, 0); //从直径两端点分别dfs
		vis[V] = true;
		dfs(V, -1, 0);
		for(int i=1; i<=n; i++)
			printf("%d\n", ans[i]);
	}





#ifdef debug
	clock_t etime = clock();
	printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
	return 0;
}


全部评论

相关推荐

小狗吃臭臭:以后用不到你设计的手机了,可惜!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
# 听劝,这个简历怎么改 #
14102次浏览 183人参与
# 面试被问“你的缺点是什么?”怎么答 #
6486次浏览 100人参与
# 水滴春招 #
16588次浏览 358人参与
# 入职第四天,心情怎么样 #
11331次浏览 63人参与
# 租房找室友 #
8035次浏览 53人参与
# 读研or工作,哪个性价比更高? #
26176次浏览 356人参与
# 职场新人生存指南 #
199273次浏览 5510人参与
# 参加完秋招的机械人,还参加春招吗? #
27030次浏览 276人参与
# 文科生还参加今年的春招吗 #
4122次浏览 31人参与
# 简历无回复,你会继续海投还是优化再投? #
48634次浏览 561人参与
# 你见过最离谱的招聘要求是什么? #
144723次浏览 829人参与
# 如果重来一次你还会读研吗 #
155720次浏览 1706人参与
# 机械人选offer,最看重什么? #
69078次浏览 449人参与
# 选择和努力,哪个更重要? #
44323次浏览 493人参与
# 如果再来一次,你还会学硬件吗 #
103650次浏览 1245人参与
# 如果你有一天可以担任公司的CEO,你会做哪三件事? #
20526次浏览 414人参与
# 招聘要求与实际实习内容不符怎么办 #
46769次浏览 494人参与
# 22届毕业,是读研还是拿外包offer先苟着 #
4652次浏览 27人参与
# 你们的毕业论文什么进度了 #
901330次浏览 8961人参与
# 软开人,你觉得应届生多少薪资才算合理? #
81380次浏览 496人参与
# 国企还是互联网,你怎么选? #
109200次浏览 853人参与
牛客网
牛客企业服务