跳到正文

题解

题解:P1670 [USACO04DEC] Tree Cutting S

#SUSPENDED#约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年8月3日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 4 分钟
获赞
3
题目
P1670

版本

  1. v1当前

题解:P1670 [USACO04DEC] Tree Cutting S

一道水绿,废话不多说直接开始讲解。

解题步骤:

首先开始思考解题方法,题目中说这是一颗树,于是直接锁定关于树的算法。然后再观察题目,“为保证破坏够大,每一个子网的牛棚数不得超过总牛棚数的一半”这句话直接告诉了我们这题所需的算法——树的重心,因为树的重心的定义正是:如果在树中选择某个节点并删除,这棵树将分为若干棵子树,统计子树节点数并记录最大值。取遍树上所有节点,使此最大值取到最小的节点被称为整个树的重心。(摘自 OI-Wiki 树的重心)

众所周知,在求树的重心时我们通常会用一个数组,比如:msims_{i} 来记录第 ii 个节点被删除后每棵子树节点数的最大值(也可以理解为:对于第 ii 个节点,以 ii 为根求 ii 的所有子树的节点数的最大值)。而这道题与树的重心模板唯一的不同在于它多了一个要求:只要破坏该节点后每一个子网的牛棚数不得超过总牛棚数的一半即可输出。因此我们只需在跑完求树的重心的 DFS 后把所有 ms≤n2ms \le \frac{n}{2} 的节点输出即可。

时间复杂度:

由于主体代码只跑了一遍 DFS 求树的重心,所以时间复杂度为 O(n+m)O(n+m)。

AC Code:

C++
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <climits>
#include <algorithm>
#include <cmath>
#include <unordered_set>
#include <map>
#include <bitset>
#include <cstdio>
#define ll long long
#define P pair<int, int>
#define MP make_pair
#define PU push_back
#define li(x) x << 1
#define ri(x) (x << 1) | 1
using namespace std;
const ll LLF = LLONG_MAX >> 2;
const int INF = INT_MAX >> 1;
const int N = 1e4 + 5;
int n, tot, head[N], son[N], ms[N];

struct Edge{
	int u, v, w, nex;
}e[N << 1];

inline ll read(){
	ll f = 1, x = 0;
	char c = getchar();
	while(c < '0' || c > '9'){if(c == '-') f = -1; c = getchar();}
	while('0' <= c && c <= '9') x = (x << 3) + (x << 1) + (ll)(c - '0'), c = getchar();
	return x * f;
}

inline void write(ll x){
    if(x < 0) putchar('-'), x = -x;
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

inline void add(int u, int v){
	e[++tot] = {u, v, 1, head[u]};
	head[u] = tot;
}

void DFS(int u, int fr){
	son[u] = 1;
	for(int i = head[u]; i; i = e[i].nex){
		int v = e[i].v;
		if(v == fr) continue;
		DFS(v, u);
		son[u] += son[v];
		ms[u] = max(ms[u], son[v]);
	}
	ms[u] = max(ms[u], n - son[u]);
}

int main(){
//	freopen("water.in.txt", "r", stdin);
//	freopen("water.out.txt", "w", stdout);
	
//	ios::sync_with_stdio(false);
//  cin.tie(0), cout.tie(0);
	
	n = read();
	for(int i = 1, u, v; i < n; ++i){
		u = read(), v = read();
		add(u, v), add(v, u);
	}
	DFS(1, 0);
	bool f = false;
	for(int i = 1; i <= n; ++i) if(ms[i] <= (n >> 1)) f = true, write(i), putchar('\n');
	if(!f) puts("NONE");
	return 0;
}

完结撒花!!!

原文
存档评论3 条抓取于