跳到正文

题解

题解:CF87D Beautiful Road

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

文章信息

发布
2026年9月8日
收录
2026年9月8日
更新
2026年11月8日
篇幅
约 4 分钟
题目
CF87D

版本

  1. v1当前

Solution

这个题的题意就是给你一个树,然后取任意的两点给这两点之间路径上权值最大的几条边的边权值累加。最后求出边权最大的几条边的边权和编号。

我们在面对没有重复边权的图时,首先按照边权进行排序,其次若一条边连着两个不相同的连通块,其所贡献的答案就是这两个连通块数量的乘积。

但是当面对有重边的树时,我们就要解决特殊情况了。当有若干条边权相同的边,并且其相连以后能构成一个连通块时如果我们一个一个更新,那么我们一开始乘的块就会偏小,导致计算的答案小了。

而这个问题的解决方案就是在处理相同边权的边时,再次按照其深度来排序。同时我们记录遍历到当前点时其深度更深的连通块的点的个数,之后进行正常合并。这样我们在后续的操作之中就能保证不会再有新的连通块连到其深度深的子树上。最后再统一计算。

Code

C++
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<stdio.h>
#include<cstdio>
#include<string>
#include<vector>
#include<queue>
#include<deque>
#include<cmath>
#include<map>
#include<set>
#define int long long
using namespace std;
const int N=2e5+5;
const int M=35;
int n,h[N],deep[N];
int fa[N],cnt[N],tmp[N];
int ans[N];
vector<int>e[N];
struct edge {
	int u,v,w,id,d;
} s[N];
int find(int x) {
	if(fa[x]==x) return x;
	return fa[x]=find(fa[x]);
}
bool cmp(edge hh,edge mm) {
	if(hh.w==mm.w) return hh.d>mm.d;
	return hh.w<mm.w;
}
void dfs(int u,int ff) {
	deep[u]=deep[ff]+1;
	for(auto v:e[u])
		if(v!=ff) dfs(v,u);
}
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin>>n;
	for(int i=1; i<=n; i++) s[i].id=fa[i]=i,cnt[i]=1;
	for(int i=1; i<n; i++) cin>>s[i].u>>s[i].v>>s[i].w;
	for(int i=1; i<n; i++) e[s[i].u].push_back(s[i].v),e[s[i].v].push_back(s[i].u);
	dfs(1,0);
	for(int i=1; i<n; i++) s[i].d=min(deep[s[i].u],deep[s[i].v]);
	sort(s+1,s+n,cmp);
	for(int i=1; i<n; i++) {
		for(int j=i; j<n; j++) {
			if(s[i].w!=s[j].w) break;
			int pos1=s[j].u,pos2=s[j].v;
			if(deep[pos1]>deep[pos2]) swap(pos1,pos2);
			tmp[j]=cnt[pos2];
			cnt[find(pos1)]+=cnt[pos2];
			fa[pos2]=find(pos1);
		}
		for(int j=i; j<n; j++) {
			if(s[i].w!=s[j].w) break;
			i=j;
			int pos1=s[j].u;
			ans[s[j].id]=tmp[j]*(cnt[find(pos1)]-tmp[j])*2;
		}
	}
	int maxx=0,num=0;
	for(int i=1; i<=n; i++)
		if(maxx<ans[i]) maxx=ans[i],num=1;
		else if(maxx==ans[i]) num++;
	cout<<maxx<<' '<<num<<endl;
	for(int i=1; i<=n; i++)
		if(ans[i]==maxx) cout<<i<<' ';
	return 0;
}
原文