重心定义:重心是指树中的一个结点,如果将这个点删除后,剩余各个连通块中节点个数的最大值最小,那么这个节点被称为树的重心。
let val = new Int32Array(200010);
let idx = 0;
let next = new Int32Array(200010);//无向图需要2倍的空间存储关系
let head = new Int32Array(100010).fill(-1);
let add = (a, b) => {
val[idx] = b;
next[idx] = head[a];//head[a]表示旧的头结点位置
head[a] = idx++;//新头结点
}
let n = 0, min = 100010;
let used = new Int32Array(100010);
let dfs = (x) => {
used[x] = 1;
let deep = 0, maxCount = 0;
for (let i = head[x]; i !== -1; i = next[i]) {
let node = val[i];
if (used[node]) continue;
let sub = dfs(node);
maxCount = Math.max(maxCount, sub);//获取子连通块的最大点数
deep += sub;
}
//计算比较剩余连通块的点数,多减1是为了减去自身节点
maxCount = Math.max(maxCount, n - deep - 1);
min = Math.min(min, maxCount);
//used[x] = 0; //不能恢复会造成死循环
return deep + 1;
}
let buf = '';
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
n = getInputNums(line)[0];
} else {
let arr = getInputNums(line);
add(arr[0], arr[1]);
add(arr[1], arr[0]);
if (lineIdx === n - 1) {
dfs(1);
console.log(min);
}
}
});
});