#虚树#bzoj 2286 洛谷 2495 消耗战

本文详细介绍了一种经典的算法题解思路,通过构建虚树即由所需点与它们的最低公共祖先组成的树,并在此基础上进行动态规划求解。文章提供了完整的代码实现,深入解析了从DFS遍历、LCA查询到虚树构建的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目


分析

这道题目需要建立虚树,也就是建一棵所需点与它们lca组成的树,在树上dp,由于题目比较经典,就直接贴代码了


代码

#include <cstdio>
#include <cctype>
#include <algorithm>
#include <cstring>
#define rr register
#define min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
const int N=250101; ll minx[N];
struct node{int y,next;}e[N<<1],E[N];
int fat[N],dep[N],ls[N],hs[N],w[N<<1],son[N],n;
int big[N],top[N],stac[N],k=1,K,dfn[N],a[N],tot;
inline signed iut(){
	rr int ans=0,f=1; rr char c=getchar();
	while (!isdigit(c)) f=(c=='-')?-f:f,c=getchar();
	while (isdigit(c)) ans=(ans<<3)+(ans<<1)+(c^48),c=getchar();
	return ans*f;
}
inline void print(ll ans){
	if (ans>9) print(ans/10);
	putchar(ans%10+48);
}
inline void add(int x,int y){E[++K]=(node){y,hs[x]},hs[x]=K;}
inline void dfs1(int x,int fa){
	dep[x]=dep[fa]+1,fat[x]=fa,son[x]=1;
	for (rr int i=ls[x],mson=-1;i;i=e[i].next)
	if (e[i].y!=fa){
		minx[e[i].y]=min(minx[x],w[i]);//维护根节点到该点的最小边权
		dfs1(e[i].y,x);
		son[x]+=son[e[i].y];
		if (son[e[i].y]>mson)
		    big[x]=e[i].y,mson=son[e[i].y];
	}
}
inline void dfs2(int x,int linp){
	dfn[x]=++tot,top[x]=linp;
	if (!big[x]) return; dfs2(big[x],linp);
	for (rr int i=ls[x];i;i=e[i].next)
	if (e[i].y!=fat[x]&&e[i].y!=big[x]) dfs2(e[i].y,e[i].y);
}
inline signed lca(int x,int y){
	while (top[x]!=top[y]){
		if (dep[top[x]]<dep[top[y]]) x^=y,y^=x,x^=y;
		x=fat[top[x]];
	}
	if (dep[x]>dep[y]) x^=y,y^=x,x^=y;
	return x;
}
inline bool cmp(int x,int y){return dfn[x]<dfn[y];}
inline ll dfs(int x){
	if (!hs[x]) return minx[x];
	rr ll ans=0;
	for (rr int i=hs[x];i;i=E[i].next)
	    ans+=dfs(E[i].y);
	hs[x]=0;
	return min(ans,minx[x]);
}
inline void Insert(int x){
	if (tot==1) {stac[++tot]=x; return;}//只有一个点直接建
	rr int Lca=lca(x,stac[tot]);
	if (Lca==stac[tot]) return;//不需要建边
	while (tot>1&&dfn[stac[tot-1]]>=dfn[Lca]) add(stac[tot-1],stac[tot]),--tot;//单调栈
	if (Lca!=stac[tot]) add(Lca,stac[tot]),stac[tot]=Lca; stac[++tot]=x;//加入该点
}
signed main(){
	n=iut();
	memset(minx,42,sizeof(minx));
	for (rr int i=1;i<n;++i){
		rr int x=iut(),y=iut(),z=iut();
		e[++k]=(node){y,ls[x]},ls[x]=k,
		e[++k]=(node){x,ls[y]},ls[y]=k,
		w[k]=w[k^1]=z;
	}
	dfs1(1,0),dfs2(1,1),tot=0;
	for (rr int m=iut();m;--m){
		K=0; rr int q=iut();
		for (rr int i=1;i<=q;++i) a[i]=iut();
		sort(a+1,a+1+q,cmp),stac[tot=1]=1;//按照dfs序排序
		for (rr int i=1;i<=q;++i) Insert(a[i]);//依次插入
		for (--tot;tot;--tot) add(stac[tot],stac[tot+1]);//建树
		print(dfs(1)),putchar(10);
	}
	return 0;
}
### 关于 BZOJ1728 Two-Headed Cows (双头牛) 的算法解析 此问题的核心在于如何通过有效的图论方法解决给定约束下的最大独立集问题。以下是详细的分析和解答。 #### 问题描述 题目要求在一个无向图中找到最大的一组节点集合,使得这些节点之间满足特定的颜色匹配条件。具体来说,每条边连接两个节点,并附带一种颜色标记(A 或 B)。对于任意一条边 \(u-v\) 和其对应的颜色 \(c\),如果这条边属于最终选取的子集中,则必须有至少一个端点未被选入该子集或者两端点均符合指定颜色关系。 #### 解决方案概述 本题可以通过 **二分枚举 + 图染色验证** 来实现高效求解。核心思想如下: 1. 假设当前最优解大小为 \(k\),即尝试寻找是否存在一个大小为 \(k\) 的合法子集。 2. 枚举每一个可能作为起点的节点并将其加入候选子集。 3. 对剩余部分执行基于 BFS/DFS 的图遍历操作,在过程中动态调整其他节点的状态以确保整体合法性。 4. 如果某次试探能够成功构建符合条件的大规模子集,则更新答案;反之则降低目标值重新测试直至收敛至最佳结果。 这种方法利用了贪心策略配合回溯机制来逐步逼近全局最优点[^1]。 #### 实现细节说明 ##### 数据结构设计 定义三个主要数组用于记录状态信息: - `color[]` : 存储每个顶点所分配到的具体色彩编号; - `used[]`: 表示某个定点是否已经被处理过; - `adjList[][]`: 记录邻接表形式表示的原始输入数据结构便于后续访问关联元素。 ##### 主要逻辑流程 ```python from collections import deque def check(k, n): def bfs(start_node): queue = deque([start_node]) used[start_node] = True while queue: u = queue.popleft() for v, c in adjList[u]: if not used[v]: # Assign opposite color based on edge constraint &#39;c&#39; target_color = (&#39;B&#39; if c == &#39;A&#39; else &#39;A&#39;) if color[u]==c else c if color[v]!=target_color and color[v]!=&#39;?&#39;: return False elif color[v]==&#39;?&#39;: color[v]=target_color queue.append(v) used[v] =True elif ((color[u]==c)==(color[v]==(&#39;B&#39;if c==&#39;A&#39;else&#39;A&#39;))): continue return True count=0 success=True for i in range(n): if not used[i]: temp_count=count+int(color[i]==&#39;?&#39; or color[i]==&#39;A&#39;) if k<=temp_count: color_copy=color[:] if bfs(i): count=temp_count break else : success=False return success n,m=list(map(int,input().split())) colors=[[&#39;?&#39;]*m]*n for _ in range(m): a,b,c=input().strip().split() colors[int(a)-1].append((int(b),c)) low ,high,res=0,n,-1 while low<=high: mid=(low+high)//2 color=[&#39;?&#39;]*n used=[False]*n if check(mid,n): res=mid low=mid+1 else : high=mid-1 print(res) ``` 上述代码片段展示了完整的程序框架以及关键函数 `check()` 的内部运作方式。它接受参数 \(k\) 并返回布尔值指示是否有可行配置支持如此规模的选择[^2]。 #### 复杂度分析 由于采用了二分查找技术缩小搜索空间范围再加上单轮 DFS/BFS 时间复杂度 O(V+E),总体性能表现良好适合大规模实例运行需求。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值