跳到正文

题解

P3304 [SDOI2013] 直径

qqqaaazzz_qwq约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月1日
收录
2025年12月12日
更新
2026年10月28日
篇幅
约 4 分钟
题目
P3304

版本

  1. v1当前

神奇做法 +1

对于第 ii 条边,如果我们把这条边删掉之后直径长度不变,就说明这不是一条必经边,否则就说明它是一条必经边。

删掉一条边之后树会被分成两部分,直接换根 DP 即可。做完了。

C++
#include <bits/stdc++.h>
#define int long long
#define FAST ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;
/*
l1[i]到子树里最远的点,距离
l2[i]到子树外最远的点,距离

z1[i]子树里面的直径
z2[i]子树外的直径,就是扣掉我之后的答案
*/
int n,q;
vector<pair<int,int> > v[1000010];
int l1[1000010],l2[1000010];
int z1[1000010],z2[1000010];

void dfs1(int d,int fa){
	int mx = 0,cmx = 0;
	for (auto i : v[d]){
		if(i.first!=fa){
			dfs1(i.first,d);
			int to = i.second+l1[i.first];
			if(to>=mx){
				cmx = mx;
				mx = to;
			}
			else if(to>=cmx) cmx = to;
			z1[d] = max(z1[d],z1[i.first]);
			l1[d] = max(l1[d],to);
		}
	}
	z1[d] = max(z1[d],mx+cmx);
	return;
}
void dfs2(int d,int fa){
	int mx = 0,cmx = 0,ccmx = 0;
	int zx = 0,czx = 0;
	for (auto i : v[d]){
		int to = (i.first==fa? l2[d]:l1[i.first]+i.second);
		if(to>=mx) ccmx = cmx,cmx = mx,mx = to;
		else if(to>=cmx) ccmx = cmx,cmx = to;
		else if(to>=ccmx) ccmx = to;
		to = (i.first==fa? z2[d]:z1[i.first]);
		if(to>=zx) czx = zx,zx = to;
		else if(to>=czx) czx = to;
	}
	for (auto i : v[d]){
		int to = (i.first==fa? l2[d]:l1[i.first]+i.second);
		if(i.first==fa) continue;
		if(to==mx) l2[i.first] = i.second+cmx;
		else l2[i.first] = i.second+mx;

		if(to==mx) z2[i.first] = cmx+ccmx;
		else if(to==cmx) z2[i.first] = mx+ccmx;
		else z2[i.first] = mx+cmx;
		to = (i.first==fa? z2[d]:z1[i.first]);
		if(to==zx) z2[i.first] = max(z2[i.first],czx);
		else z2[i.first] = max(z2[i.first],zx);

		dfs2(i.first,d);
	}
}

signed main()
{
	FAST;
	cin >> n;
	for (int i=1;i<=n-1;i++){
		int x,y,z;
		cin >> x >> y >> z;
		v[x].push_back({y,z});
		v[y].push_back({x,z});
	}
	dfs1(1,0);
	dfs2(1,0);
	int ans = z1[1];
	cout << ans << "\n";
	int cnt = 0;
	for (int i=2;i<=n;i++){
		if(max(z1[i],z2[i])!=ans) ++cnt;
	}
	cout << cnt << "\n";
	return 0;
}
原文