跳到正文

题解

[ABC368D] Minimum Steiner Tree 题解

Seqfrel约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年8月25日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟

版本

  1. v1当前

[ABC368D] Minimum Steiner Tree 题解

前置知识:搜索

题目大意

给定一棵树,以及 KK 个必选结点。求如何在 KK 个结点都被包含的情况下,构建一棵结点最少的树。

解题思路

考虑从一个根节点遍历这棵树。设当前遍历到的结点为 uu,uu 的子结点为 vv。当以 vv 为根的子树有需要选的结点时,vv 和 uu 都需要选。由此遍历完一遍后,所有需要选的结点就都被打上标记了。

不过有一个点需要注意,那就是遍历根节点的选择。为了保证根节点一定是目标树上的结点而不是从哪里斜插过来的无用结点,我们这里直接用一个必选结点当做根结点来遍历,这样就不会有问题了。

时间复杂度为 O(n)O(n) 比某人的数剖要好多了。

代码实现

这里我们可以将 dfs 定义为 bool 类型,方便判断是否需要选取。

C++
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=2e5+10;
struct Node{
	int to,nxt;
}e[2*maxn];
int n,k,r,ans;
int h[maxn],tot;
bool vis[maxn],visv[maxn],visc[maxn];
void Add(int u,int v){
	tot++;
	e[tot].to=v;
	e[tot].nxt=h[u];
	h[u]=tot;
}
bool dfs(int root,int fa){
	vis[root]=1;
	for(int i=h[root];i;i=e[i].nxt){
		int v=e[i].to;
		if(v==fa) continue;
		if(dfs(v,root)) visc[root]=1;
	}
	if(visv[root]||visc[root]){
		visc[root]=1;
		return 1;
	}else return 0;
}
int main(){
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n-1;i++){
		int a,b;
		scanf("%d%d",&a,&b);
		Add(a,b);
		Add(b,a); 
	}
	for(int i=1;i<=k;i++){
		int V;
		scanf("%d",&V);
		visv[V]=1;
		r=V;
	} 
	dfs(r,0);
	for(int i=1;i<=n;i++){
		if(visc[i]) ans++;
	}
	cout<<ans;
	return 0;
} 

注意事项

老生常谈双向边。

原文