跳到正文

个人记录

代码分析0x05

hyk0YF0Gamer约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年9月4日
收录
2026年9月7日
更新
2026年11月8日
篇幅
约 5 分钟

版本

  1. v1当前

https://www.luogu.com.cn/article/6afb401u

P2726

C++
#include <cstdio>
#include <algorithm>
#define INF 2147483647
using namespace std;
#define Open(s) freopen(s".in","r",stdin);freopen(s".out","w",stdout);
#define Close fclose(stdin);fclose(stdout);
int s, w; char ch;
inline int read(){
	s = 0; ch = getchar();
	while(ch < '0' || ch > '9') ch = getchar(); 
	while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar();}
	return s;
}
//以上为无用部分 
const int MAXN = 100010;
struct Edge{
	int next, to;
}e[MAXN << 1];
int head[MAXN], num, a[MAXN], size[MAXN], f[MAXN], val[MAXN], dep[MAXN], son[MAXN], Sson[MAXN], A, B, n, root, ans = INF, cut;
inline void Add(int from, int to){//加边,但双向 
	e[++num].to = to; e[num].next = head[from]; head[from] = num;
	e[++num].to = from; e[num].next = head[to]; head[to] = num;
}
int getsize(int u, int fa){//dfs换皮再战,预处理整棵树和第一、第二重儿子 
	size[u] = a[u]; f[u] = fa; dep[u] = dep[fa] + 1;
	for(int i = head[u]; i; i = e[i].next)
		if(e[i].to != fa){
			getsize(e[i].to, u);
			size[u] += size[e[i].to];
			val[u] += val[e[i].to] + size[e[i].to];
			if(size[e[i].to] > size[son[u]]){//重儿子 
              Sson[u] = son[u];
              son[u] = e[i].to;
            }
            else if(size[e[i].to] > size[Sson[u]])//次重儿子 
              Sson[u] = e[i].to;
		}
}
void getans(int u, int now, int all, int &res){//随后便可计算答案了 
    res = min(res, now);
    int v = son[u];
    if(v == cut || size[Sson[u]] > size[son[u]]) v = Sson[u];   //如果size变化后次大大于最大
    if(!v) return;
    if(size[v] * 2 > all) getans(v, now + all - size[v] - size[v], all, res);  //如果size[v]*2<=all就没有继续往下走的意义了,因为此时u一定最优
}
int solve(int u){
    for(int i = head[u]; i; i = e[i].next)
       if(e[i].to != f[u]){
         cut = e[i].to;  //断边
         A = B = INF;
         for(int now = u; now; now = f[now]) size[now] -= size[e[i].to];  //自下而上修改其父亲size
         getans(1, val[1] - val[e[i].to] - dep[e[i].to] * size[e[i].to], size[1], A);
         getans(e[i].to, val[e[i].to], size[e[i].to], B);    //求两个集合的答案
         ans = min(ans, A + B);
         for(int now = u; now; now = f[now]) size[now] += size[e[i].to];   //回溯
         solve(e[i].to);
       }
}
int main(){
	//Open("practice");
	n = read(); dep[0] = -1;
	for(int i = 1; i < n; ++i) Add(read(), read());
	for(int i = 1; i <= n; ++i) a[i] = read();
	getsize(1, 0);
	solve(1);
	printf("%d\n", ans);
	return 0;
}
原文