POJ 1655 Balancing Act [求树的重心]

本文探讨了在树形结构中寻找重心的概念及其算法实现,包括树形DP方法和复杂度分析。

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. 

题意:给出一棵树,求该树的重心。

解法:算是模板题了,已知以重心为根,其儿子子树的最大SIZE最小,那么可以考虑树形DP,用一个MAXV[]去记录以X为重心时,儿子子树的最大SIZE。复杂度为O(N)

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<iostream>
#include<stdlib.h>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<bitset>
#pragma comment(linker, "/STACK:1024000000,1024000000")
template <class T>
bool scanff(T &ret){ //Faster Input
    char c; int sgn; T bit=0.1;
    if(c=getchar(),c==EOF) return 0;
    while(c!='-'&&c!='.'&&(c<'0'||c>'9')) c=getchar();
    sgn=(c=='-')?-1:1;
    ret=(c=='-')?0:(c-'0');
    while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
    if(c==' '||c=='\n'){ ret*=sgn; return 1; }
    while(c=getchar(),c>='0'&&c<='9') ret+=(c-'0')*bit,bit/=10;
    ret*=sgn;
    return 1;
}
#define inf 1073741823
#define llinf 4611686018427387903LL
#define PI acos(-1.0)
#define lth (th<<1)
#define rth (th<<1|1)
#define rep(i,a,b) for(int i=int(a);i<=int(b);i++)
#define drep(i,a,b) for(int i=int(a);i>=int(b);i--)
#define gson(i,root) for(int i=ptx[root];~i;i=ed[i].next)
#define tdata int testnum;scanff(testnum);for(int cas=1;cas<=testnum;cas++)
#define mem(x,val) memset(x,val,sizeof(x))
#define mkp(a,b) make_pair(a,b)
#define findx(x) lower_bound(b+1,b+1+bn,x)-b
#define pb(x) push_back(x)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;


#define NN 20020
int n;
int ptx[NN],lnum;
struct edge{
    int v,next,w;
    edge(){}
    edge(int v,int next,int w){
        this->v=v;
        this->next=next;
        this->w=w;
    }
}ed[NN*2];
void addline(int x,int y,int w){
    ed[lnum]=edge(y,ptx[x],w);
    ptx[x]=lnum++;
}


int f[NN],sz[NN];
int dfs(int x,int fa){
    f[x]=fa;
    sz[x]=0;
    gson(i,x){
        int y=ed[i].v;
        if(y==fa)continue;
        sz[x]+=dfs(y,x);
    }
    sz[x]++;
    return sz[x];
}


int maxv[NN],maxval,center;
void getCenter(int r,int x){
    maxv[x]=0;
    gson(i,x){
        int y=ed[i].v;
        if(y==f[x])continue;
        getCenter(r,y);
        maxv[x]=max(maxv[x],sz[y]);
    }
    maxv[x]=max(maxv[x],sz[r]-sz[x]);
    if(maxv[x]<maxval||(maxv[x]==maxval&&x<center))
        center=x,maxval=maxv[x];
}

inline int getCenter(int x){
    maxval=inf;
    getCenter(x,x);
    return center;
}




void init(){
    lnum=0;
    mem(ptx,-1);
}

int main(){
    tdata{
        init();
        scanff(n);
        rep(i,1,n-1){
            int x,y;
            scanff(x);
            scanff(y);
            addline(x,y,1);
            addline(y,x,1);
        }
        dfs(1,0);
        int ans=getCenter(1);
        printf("%d %d\n",ans,maxv[ans]);
    }
}


/*
3
5
1 2
2 3
3 4
4 5
7
2 6
1 2
1 4
4 5
3 7
3 1
4
1 2
2 3
3 4

*/




### POJ 树的重心问题解法 树的重心问题在POJ平台上的经典题目是 **POJ1655**。该问题的核心在于通过深度优先搜索(DFS)计算每个节点的子树大小,并进一步确定删除某个节点后,剩余部分的最大子树大小。最终目标是找到一个节点,使得删除该节点后,剩余的最大子树大小最小。 以下是关于该问题的具体解法和代码实现: #### 问题描述 给定一棵树,要找到树的重心树的重心定义为:删除某个节点后,所有生成的连通分量中,最大连通分量的节点数尽可能小。如果存在多个满足条件的节点,则输出编号最小的节点。 #### 解法思路 1. 使用 DFS 遍历整棵树,计算每个节点的子树大小 `son[u]`。 2. 在 DFS 过程中,对于每个节点 `u`,记录其所有子树的最大节点数 `Max`。 3. 计算当前节点 `u` 的父节点延伸出去的节点数目 `n - son[u]`。 4. 确定当前节点 `u` 删除后,剩余的最大子树大小 `tmp = max(Max, n - son[u])`。 5. 更新答案,选择使得 `tmp` 最小的节点作为重心。若 `tmp` 相等,则选择编号较小的节点。 #### 代码实现 以下是一个基于 C++ 的完整实现: ```cpp #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 20005; int head[N], top = 0; int n; int son[N]; int ans, point; struct Edge { int v, next; } edge[N * 2]; void init() { memset(head, -1, sizeof(head)); top = 0; memset(son, 0, sizeof(son)); ans = n + 1; // 初始化为一个较大值 } void addedge(int u, int v) { edge[top].v = v; edge[top].next = head[u]; head[u] = top++; } void dfs(int u, int fa) { son[u] = 1; int Max = 0; for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].v; if (v == fa) continue; dfs(v, u); son[u] += son[v]; Max = max(Max, son[v]); } int tmp = max(Max, n - son[u]); if (tmp < ans || (tmp == ans && u < point)) { ans = tmp; point = u; } } int main() { int T; scanf("%d", &T); while (T--) { init(); scanf("%d", &n); int u, v; for (int i = 1; i < n; i++) { scanf("%d%d", &u, &v); addedge(u, v); addedge(v, u); } dfs(1, -1); printf("%d %d\n", point, ans); } return 0; } ``` #### 关键点解释 1. **初始化**:使用 `init()` 函数清空全局变量,确保每次测试用例独立运行[^3]。 2. **边的存储**:采用邻接表存储树的结构,便于快速访问每个节点的子节点。 3. **DFS 遍历**:通过递归方式计算每个节点的子树大小,并更新最大子树大小。 4. **结果更新**:在遍历过程中,实时更新最优解,确保最终答案满足题意。 #### 时间复杂度 - **DFS 遍历**:每个节点和边仅被访问一次,时间复杂度为 \(O(n)\)。 - **总复杂度**:对于多组测试数据,时间复杂度为 \(O(T \cdot n)\),其中 \(T\) 是测试用例数量,\(n\) 是节点数量。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值