java计算一个多边形的重心_AcWing 846. 树的重心--Java 面向对象写法,简单易理解...

import java.util.Arrays;

import java.util.Scanner;

public class Main {

static boolean[] st;

static int ans;

static int N;

static class Graph {

int[] h, e, ne;

int idx;

int n;

public Graph(int n) {

this.n = n;

h = new int[n];

e = new int[2 * n];

ne = new int[2 * n];

Arrays.fill(h, -1);

}

public void add(int a, int b) {

e[idx] = b; ne[idx] = h[a]; h[a] = idx++;

}

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

N = sc.nextInt();

ans = N;

Graph g = new Graph(N + 1);

st = new boolean[N + 1];

for (int i = 0; i < N - 1; i++) {

int a = sc.nextInt(), b = sc.nextInt();

g.add(a, b);

g.add(b, a);

}

dfs(g, 1);

System.out.println(ans);

}

// 以 u 为跟的节点数之和

private static int dfs(Graph g, int u) {

st[u] = true; // 已经遍历第u号节点

int sum = 0, size = 0; // sum 表示 u 节点下节点的总数, size 表示去掉u之后最大的块

for (int i = g.h[u]; i != -1; i = g.ne[i]) {

int j = g.e[i];

if (st[j]) continue;

int s = dfs(g, j);

size = Math.max(size, s);

sum += s;

}

size = Math.max(size, N - sum - 1);

ans = Math.min(ans, size);

return sum + 1;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值