BZOJ 1907: 树的路径覆盖

题目大意:

求一棵树的最小路径覆盖。

题解:

f[x][0/1/2]表示以i为根的子树中i连出了几条边的最小路径覆盖。

代码:

#include<cstdio>
#include<algorithm>
using namespace std;
int cnt,last[1000005],f[1000005][3];
struct node{
	int to,next;
}e[1000005];
void add(int a,int b){
	e[++cnt].to=b;
	e[cnt].next=last[a];
	last[a]=cnt;
}
void dfs(int x,int fa){
	f[x][0]=f[x][1]=f[x][2]=0;
	for (int i=last[x]; i; i=e[i].next){
		int V=e[i].to;
		if (V==fa) continue;
		dfs(V,x);
		int t0=f[x][0],t1=f[x][1],t2=f[x][2],tmp=min(f[V][0]+1,min(f[V][1]+1,f[V][2]+1));
		f[x][0]+=tmp;
		f[x][1]=min(t1+tmp,t0+min(f[V][0],f[V][1]));
		f[x][2]=min(t2+tmp,t1+min(f[V][0],f[V][1]));
	}
}
int main(){
	int t;
	scanf("%d",&t);
	while (t--){
		int n;
		scanf("%d",&n);
		cnt=0;
		for (int i=1; i<=n; i++) last[i]=0;
		for (int i=1; i<n; i++){
			int x,y;
			scanf("%d%d",&x,&y);
			add(x,y);
			add(y,x);
		}
		dfs(1,0);
		printf("%d\n",min(f[1][1]+1,f[1][2]+1));
	}
	return 0;
}

  

转载于:https://www.cnblogs.com/silenty/p/8745575.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值