树的直径 两次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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值