其他分享
首页 > 其他分享> > 【YBTOJ】最长距离

【YBTOJ】最长距离

作者:互联网

最长距离

题目大意:

给出一个以 1 为根的 \(n\) 个结点的树,树边有权值,求出每个结点与相距最远结点间的距离 \(s_i\)。

正文:

有一条性质:每个节点相距最远的节点一定是树的直径的端点。

那么搜索三次:找端点、统答案。

代码:

const int N = 1e4 + 10;

inline ll Read()
{
	ll x = 0, f = 1;
	char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = -f, c = getchar();
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
	return x * f;
}

int n; 

struct edge
{
	int to, nxt; ll val;
} e[N << 1];
int head[N], tot;
void add(int u, int v, ll w)
{
	e[++tot] = (edge) {v, head[u], w}, head[u] = tot;
}

ll f[N], ans, Max, root;
void dfs(int u, int fa, int len)
{
	if (Max < len) root = u, Max = len;
	for (int i = head[u]; i; i = e[i].nxt)
	{
		int v = e[i].to;
		if (v == fa) continue;
		dfs (v, u, len + e[i].val);
		f[v] = max(f[v], len + e[i].val);
	}
	return;
}

int main()
{
	while(~scanf ("%d", &n))
	{
		Max = root = 0;
		tot = 0; 
		memset (head, 0, sizeof head);
		memset (f, 0, sizeof f);
		for (int i = 2; i <= n; i++)
		{
			int v = Read();ll w = Read();
			add(i, v, w), add(v, i, w);
		}
		
		dfs(1, 0, 0);
		dfs(root, 0, 0);
		dfs(root, 0, 0);
		
		for (int i = 1; i <= n; i++)
			printf ("%lld\n", f[i]);
	}
	return 0;
}

标签:结点,端点,YBTOJ,ll,while,&&,长距离,getchar
来源: https://www.cnblogs.com/GJY-JURUO/p/15004775.html