正睿19冬令营&省选线上集训附加赛2

1 篇文章 0 订阅

T1

树型dp 推导如下(回去再挂照片)

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
const int N = 5e4 + 5;
const int inf = 1e9;

struct Edge{
	int v, next;
}edge[N << 1];
int esize, head[N];
inline void addedge(int x, int y){
	edge[++esize] = (Edge){y, head[x]};
	head[x] = esize;
}

int w[N];
int f[N], g[N];//f--all 1 g--both 1 and 2
int n;
int anss, ansm;

inline void update(int ss, int mm){
	//printf("update %d %d\n", ss, mm);
	if(ss * ansm < anss * mm){
		anss = ss; ansm = mm;
	}
}

void dfs(int x, int ff){
	if(w[x] == 1) f[x] = g[x] = 1;
	if(w[x] == 2) g[x] = 1;
	
	for(int i = head[x], vv; ~i; i = edge[i].next){
		vv = edge[i].v; if(vv == ff) continue;
		
		dfs(vv, x);
		
		update(2, g[x] + f[vv]);
		update(2, g[vv] + f[x]);
		update(1, f[x] + f[vv]);
		
		if(w[x] == 1){
			f[x] = max(f[x], f[vv] + 1);
			g[x] = max(g[x], g[vv] + 1);
		}
		if(w[x] == 2){
			g[x] = max(g[x], f[vv] + 1);
		}
	}
}

int gcd(int x, int y){
	return y ? gcd(y, x % y) : x;
}

inline void print(){
	int d = gcd(anss, ansm);
	anss /= d, ansm /= d;
	printf("%d/%d\n", anss, ansm);
}

inline void init(){
	memset(head, -1, sizeof(head));
	anss = inf, ansm = 1;
	esize = 0;
	memset(f, 0, sizeof(f));
	memset(g, 0, sizeof(g));
}

int main(){
	int T;
	scanf("%d", &T);
	while(T--){
		init();
		scanf("%d", &n);
	
		for(int i = 1; i <= n; ++i){
			scanf("%d", &w[i]);
			anss = min(anss, w[i]);
		}
		for(int i = 1, x, y, z; i < n; ++i){
			scanf("%d%d", &x, &y);
			addedge(x, y); addedge(y, x);
		}
		dfs(1, 0);
		print();
	}
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值