poj1655Balancing Act(树的重心)

IGBT基础知识 IGBT 阅读详情

Language:
Balancing Act
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9418 Accepted: 3941

Description

Consider a tree T with N (1 <= N <= 20,000) nodes numbered 1...N. Deleting any node from the tree yields a forest: a collection of one or more trees. Define the balance of a node to be the size of the largest tree in the forest T created by deleting that node from T. 
For example, consider the tree: 

Deleting node 4 yields two trees whose member nodes are {5} and {1,2,3,6,7}. The larger of these two trees has five nodes, thus the balance of node 4 is five. Deleting node 1 yields a forest of three trees of equal size: {2,6}, {3,7}, and {4,5}. Each of these trees has two nodes, so the balance of node 1 is two. 

For each input tree, calculate the node that has the minimum balance. If multiple nodes have equal balance, output the one with the lowest number. 

Input

The first line of input contains a single integer t (1 <= t <= 20), the number of test cases. The first line of each test case contains an integer N (1 <= N <= 20,000), the number of congruence. The next N-1 lines each contains two space-separated node numbers that are the endpoints of an edge in the tree. No edge will be listed twice, and all edges will be listed.

Output

For each test case, print a line containing two integers, the number of the node with minimum balance and the balance of that node.

Sample Input

1
7
2 6
1 2
1 4
4 5
3 7
3 1

Sample Output

1 2

Source




代码


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>

#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)

#define eps 1e-8
typedef __int64 ll;

using namespace std;

#define N 20005

int num[N],dp[N];
int head[N],k;
int n;

struct stud{
  int to,next;
}e[N*2];

inline void add(int u,int v)
{
	e[k].to=v;
	e[k].next=head[u];
	head[u]=k++;
}

void dfs(int x,int pre)
{
    dp[x]=0;
    num[x]=1;
    int i;
    for(i=head[x];i!=-1;i=e[i].next)
	{
		int to=e[i].to;
		if(to==pre) continue;
		dfs(to,x);

		dp[x]=max(dp[x],num[to]);
		num[x]+=num[to];
	}

	dp[x]=max(dp[x],n-num[x]); //例如树是 1 2 3 4 5,没有这一步 dp[5]就是0
}

int main()
{
	int i,j,t;
	scanf("%d",&t);
	while(t--)
	{
		k=0;
		memset(head,-1,sizeof(head));

		scanf("%d",&n);

		int u,v;
		for(i=1;i<n;i++)
		{
			scanf("%d%d",&u,&v);
			add(u,v);
			add(v,u);
		}

		dfs(1,-1);

		int ans1=1,ans2=dp[1];

		for(i=2;i<=n;i++)
			if(dp[i]<ans2)
		{
			ans1=i;
			ans2=dp[i];
		}

		printf("%d %d\n",ans1,ans2);

	}
	return 0;
}








STM32硬件SPI驱动W5500以太网模块全流程(附避坑指南) 本文详细介绍了STM32硬件SPI驱动W5500以太网模块的全流程,包括硬件架构设计、SPI接口选型、官方驱动移植、网络协议栈配置与优化等关键步骤。通过实战案例和性能对比数据,帮助开发者快速实现稳定高效的网络连接,特别提供了常见问题排查指南和性能调优技巧。 阅读详情

相关推荐

赴美参加学术会议办理流程

有幸能在研究生阶段获得学校资助出国参加学术会议,首先要感谢学校的支持,以及学院和实验室的各位老师~ 接下来说下参会整个准备过程: 本人在接到论文录用通知后,就开始办理相关手续。因为会议地点是美国夏威夷,而且录用通知时间与会议召开时间只隔两个月左右,所以接下来两个月时间要办好学校出国申请手续,赴美签证,因为专业原因,据说签证不好办,所以时间比较紧。学校出国申请和签证相关材料是并行进行的,赴美花费...

xingxin_xu的博客 3194

POJ - 1655 (点分治-树的重心)

题目:https://vjudge.net/contest/307753#problem/D 题意:给你一棵树,让你求出一个点,让他的最大子树的节点数尽量小 思路:最大子树节点数尽量小,一看就是树的重心, 然后随便套个原来的点分治模板即可 #include<cstdio> #include<cstring> #include<cmath&...

weixin_30649641的博客 168

YOLOv8 + TensorRT 实战:手把手教你用 C++ 实现实时视频流目标检测(附完整项目代码)

本文详细介绍了如何将YOLOv8与TensorRT结合,通过C++实现实时视频流目标检测的全流程。从环境配置、模型转换优化到视频处理架构设计,手把手教你构建高性能检测系统,并附完整项目代码。特别针对Windows平台下的TensorRT模型加速部署提供了实用技巧和性能优化方案。

weixin_29051193的博客 345

poj 1655 Balancing Act(树dp)

Balancing Act Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8095   Accepted: 3341 Description Consider a tree T with N (1 <= N <= 20,000) nodes numbered

街角的花街糖 686

基于RK3588边缘计算平台的人数统计系统设计与实现

针对人数统计场景优化的YOLOv5模型完整的模型转换和部署流程高效的嵌入式推理优化方案低成本、低功耗的部署方案实时性强,满足工业应用需求可扩展性好,适配多种应用场景引入注意力机制,提高小目标检测能力结合多模态信息,增强系统鲁棒性开发可视化管理平台,提升用户体验随着边缘计算和AIoT技术的快速发展,基于深度学习的智能视觉系统必将在更多领域发挥重要作用。本项目为相关应用的开发和部署提供了有价值的参考,为推动人工智能技术的产业化应用做出了积极贡献。

LXY_LOVE36的博客 145

主成分分析(PCA)简洁高效MATLAB实现详解

本文介绍了一个简洁高效的PCA算法实现。该实现通过SVD分解计算主成分,避免了显式协方差矩阵计算,支持两种降维方式:固定维度或按能量比例自动选择。核心步骤包括数据中心化、SVD分解和维度选择,代码量少但功能完整,适用于数据预处理、降维和特征提取等任务。实现中考虑了稀疏矩阵转换、默认参数处理等细节,可直接应用于MATLAB环境。

m0_62153576的博客 63

POJ-1655-树的重心

树的重心模板题 #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <map> #include <queue> #include <functional> #include <vector> #include <stack> #inc

lifeforge的博客 245

【openGauss实战1】openGauss基于CentOS8的部署

基于openGauss数据库在CentOS8上的安装实践。

IT邦德 3050

Poj 1655 【树的重心】

题目链接:http://poj.org/problem?id=1655 题解: 一开始建树时是取小的点指向大的点,然后一直WA后来发现这样建树是有问题的,可能会有(1,3)(2,3)这种出现1->3,2->3导致1、2不联通的情况出现。 #include #include #include #include #include #include #include #inc

t51645的博客 412

n8n智能体开发:Microsoft Outlook 节点

使用 Microsoft Outlook 节点可以自动化 Microsoft Outlook 工作流程,并将其与其他应用程序集成。n8n 内置支持多种 Microsoft Outlook 功能,包括创建、更新、删除和获取文件夹、邮件及草稿等操作。

王国平的博客 570

科研项目数据抓取:Python爬虫实现与分析

本文详细介绍了如何使用Python爬虫抓取科研项目的数据,涵盖了从目标数据源选择到数据存储与分析的整个过程。通过使用。

2201_76125261的博客 1710

Balancing Act (树形dp 求树的重心板题)

题目:Balancing Act  Consider a tree T with N (1 <= N <= 20,000) nodes numbered 1...N. Deleting any node from the tree yields a forest: a collection of one or more trees. Define the balance of a node to

sdau164185的博客 483

Python爬虫实战:利用Playwright+Asyncio高效获取淘宝商品价格变化曲线

本文将详细介绍如何使用Python最新技术栈(Playwright+Asyncio)构建一个高效的淘宝商品价格监控爬虫系统。我们将从爬虫基础知识讲起,逐步深入到反爬应对策略、数据存储与分析,最终实现价格变化曲线的可视化展示。文章包含完整的代码实现和详细的技术解析,适合中高级Python开发者学习参考。关键词:Python爬虫、Playwright、Asyncio、淘宝价格监控、数据可视化支持多浏览器(Chromium, Firefox, WebKit)更快的执行速度更丰富的API。

2201_76125261的博客 244

poj 1655 Balancing Act 【树的重心】

知识点:树的重心 定义:以这个点为根,那么所有的子树(不算整个树自身)的大小都不超过整个树大小的一半。 性质: 性质 1 :树中所有点到某个点的距离和中,到重心的距离和是最小的,如果有两个距离和,他们的距离和一样。 性质 2 :把两棵树通过某一点相连得到一颗新的树,新的树的重心必然在连接原来两棵树重心的路径上。 性质 3 :一棵树添加或者删除一个节点,树的重心最多只移动一

大神养成中..... 1761

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

poj 1655 Balancing Act(树的重心+dfs)

poj 1655 Balancing Act(树的重心+dfs) Consider a tree T with N (1 &amp;lt;= N &amp;lt;= 20,000) nodes numbered 1…N. Deleting any node from the tree yields a forest: a collection of one or more trees. Define the ba...

weixin_43179892的博客 268

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

【POJ 1655】Balancing Act 【树的重心】

【POJ 1655】Balancing Act 求树的重心模板~

Regina8023 1819

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

【树的重心】 POJ 1655 Balancing Act

Balancing Act Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 11911   Accepted: 5019 Description Consider a tree T with N (1 <= N <= 20,000) nodes numbered 1

曜雨丶的博客 779

POJ1655 Balancing Act 求树的重心

题目链接:http://poj.org/problem?id=1655 题目大意:树的重心:找到一个点作为新的树根,其所有的子树中最大子树的节点数最少,那么这个点就是这个树的重心。树的重心的意义在于,删去重心后,生成的多棵树尽可能平衡。 分析:一次搜索即可。DFS每一个点s,找出其各个子树的节点数,纪录最大值son[s],然后比较balance=max(son[s],n-son

AC_Gibson的专栏 583

poj1655 Balancing Act 求树的重心

http://poj.org/problem?id=1655 Balancing Act Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 9072   Accepted: 3765 Description Consider a tree T with

597

poj 1655 Balancing Act 图论基础 树的重心

图论基础 树的重心

ned_chu的博客 783

Balancing Act POJ - 1655 树形dp 树的重心

题解 题目大意 给你一个n的顶点n-1条边的无根树 让你找出树的重心 并求出平衡值 树的重心 找到一个点,其所有的子树中最大的子树节点数最少,那么这个点就是这棵树的重心 平衡值为最大子树节点数量 使用树形dp求解 siz[i]表示i的子树的大小 d[i]表示以i为重的平衡值 求解过程中任选一点为树根 siz使用DFS回溯求解siz[i] = 1 + ∑siz[子树] 在DFS过程中可以同时求出d[...

CaprYang的博客 460

【POJ】1655 Balancing Act 树的重心

传送门:【POJ】1655 Balancing Act 题目分析:树的重心水题。 代码如下:

poursoul 1182

poj 1655 Balancing Act 寻找树的重心

就是寻找树的重心的果题。 http://poj.org/problem?id=1655 #include <map> #include <set> #include <queue> #include <cmath> #include <cstdio> #include <cstring> #include <cstdlib> #include <iostream> #include <algor

NM的专栏 437

【POJ 1655】Balancing Act (树的重心)

如果您不清楚树的重心有关定义及性质,或想水一批树的重心经典题目,戳这里 简述题意:给定一棵树,求树的重心的编号以及重心删除后得到的最大子树的节点个数size,如果size相同就选取编号最小的. 算法:树型DP,树的重心(裸题) 难度:NOIP 题解: 树的重心定义为:找到一个点,其所有的子树中最大的子树节点数最少,那么这个点就是这棵树的重心. 这就够了! 代码如下: #inclu...

01232012的博客 351

poj1655—Balancing Act(树的重心)

题目链接:传送门 Balancing Act Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 14208   Accepted: 6008 Description Consider a tree T with N (1 <= N <= 20,000)

zhiyuanjiang的博客 297

【POJ1655】Balancing Act【树的重心】

题意: 求树的重心。 做点分治前先做的一个题。 #include #include using namespace std; const int maxn = 20005, inf = 0x3f3f3f3f; int n, head[maxn], cnt, size[maxn], id, ans; struct _edge { int v, next; } g[

BraketBN 460
上一篇: hdu2196Computer(树形dp)
下一篇: poj 3264 Balanced Lineup(简单线段树 或 rmq)
左眼皮跳跳~
博客等级 码龄13年 17粉丝 400原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值