跳到正文

题解

题解 P4886 【快递员】

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
获赞
3
题目
P4886

版本

  1. v1当前

对淀粉质思想的运用qwqqwq

我们考虑对于一个点对(u,v)(u,v),若其为最大值,且点rtrt在其路径上,那么显然答案是不能再小的,否则答案是可能可以更小的。

具体类比下来,对于一个rtrt而言,其肯定为答案有且仅有两种情况:

1.1.距离最远的点对(u,v)(u,v)满足其分居在rtrt的两棵子树内

2.2.存在两个及以上的点对(u,v)(u,v)满足这两个点在同一颗子树内,但是这多个子树不是同一颗。

否则,如果为如下情况,答案是可能会更小。

3.3.对于所有的距离最长的两个点对(u,v)(u,v)都有其处于同一颗子树

那么我们就往那颗子树内走即可。

但是直接走下来复杂度还是O(n2)O(n^2)的,因为我们每次统计答案都是暴力统计。

考虑每次对那颗子树求一个重心,那么就可以将问题规模缩小一半,因为我们可以保证可能更小的点就在这颗子树内。

复杂度O((n+m)log⁡n)O((n+m)\log n)

C++
#include<bits/stdc++.h>
using namespace std;
#define Next( i, x ) for( register int i = head[x]; i; i = e[i].next )
#define rep( i, s, t ) for( register int i = s; i <= t; ++ i )
#define re register
int read() {
	char cc = getchar(); int cn = 0, flus = 1;
	while(cc < '0' || cc > '9') {  if( cc == '-' ) flus = -flus;  cc = getchar();  }
	while(cc >= '0' && cc <= '9')  cn = cn * 10 + cc - '0', cc = getchar();
	return cn * flus;
}
const int N = 1e5 + 5 ;
struct E {
	int to, next, w ;
} e[N * 2] ;
int head[N], dis[N], fr[N], ed[N], Ans, cnt, n, m ;
int rt, sum, vis[N], sz[N], dp[N], book[N] ;
void add( int x, int y, int z ) {
	e[++ cnt] = (E){ y, head[x], z }, head[x] = cnt ,
	e[++ cnt] = (E){ x, head[y], z }, head[y] = cnt ;
}
void get_rt( int x, int fa ) {
	sz[x] = 1, dp[x] = 1 ;
	Next( i, x ) {
		int v = e[i].to ; if( v == fa || vis[v] ) continue ;
		get_rt( v, x ), sz[x] += sz[v], dp[x] = max( dp[x], sz[v] ) ;
	}
	dp[x] = max( dp[x], sum - sz[x] ) ;
	if( dp[x] < dp[rt] ) rt = x ;
}
void dfs( int x, int fa, int p ) {
	book[x] = p ;
	Next( i, x ) {
		int v = e[i].to ; if( v == fa ) continue ;
		dis[v] = e[i].w + dis[x], dfs( v, x, p ) ;
	}
}
void out() {
	printf("%d\n", Ans ) ; exit(0) ;
}
void solve( int x ) {
	if( vis[x] ) out() ;
	vis[x] = 1, dis[x] = 0 ;
	Next( i, x ) {
		int v = e[i].to ; dis[v] = dis[x] + e[i].w, dfs( v, x, v ) ;
	}
	int Mx = 0, zk = 0, chk = 0 ;
	rep( i, 1, m ) {
		int u = fr[i], v = ed[i] ;
		if( dis[u] + dis[v] == Mx ) {
			if( book[u] != book[v] ) zk = 1 ;
			if( book[u] == book[v] && book[u] != chk ) zk = 1 ;
		}
		if( dis[u] + dis[v] > Mx ) {
			Mx = dis[u] + dis[v], zk = 0 ;
			if( book[u] != book[v] ) zk = 1 ;
			if( book[u] == book[v] ) chk = book[u] ;
		}
	}
	Ans = min( Ans, Mx ) ;
	if( zk ) out() ;
	else {
		rt = 0, sum = dp[0] = sz[chk], get_rt( chk, x ) ;
		solve( rt ) ;
	}
}
signed main()
{
	n = read(), m = read() ; int x, y, z ;
	rep( i, 2, n ) x = read(), y = read(), z = read(), add( x, y, z ) ;
	rep( i, 1, m ) fr[i] = read(), ed[i] = read() ;
	rt = 0, dp[0] = sum = n, get_rt( 1, 0 ), Ans = 23333333 ;
	solve( rt ) ;
	return 0;
}
原文