疏散人群-京东2019笔试题
体育场突然着火了,现场需要紧急疏散,但是过道真的是太窄了,同时只能容许一个人通过。
现在知道了体育场的所有座位分布,座位分布图是一棵树,已知每个座位上都做了一个人,安全出口在树的根部,也就是1号结点的位置上。
其他结点上的人每秒都能向树根部前进一个结点,但是除了安全出口以外,没有任何一个结点能够同时容纳两个及以上的人。
这就需要一种策略来使得人群尽快疏散。
请问在采取最优策略的情况下,体育场最快可以在多长时间内完成疏散。
输入格式
第一行包含整数n,表示树的结点数量。
接下来n-1行,每行包含两个整数x和y,表示x和y结点之间存在一条边。
输出格式
输出一个正整数表示最短疏散时间。
数据范围
1≤n≤(10^5),
1≤y≤x≤n
输入样例:
6
2 1
3 2
4 3
5 2
6 1
输出样例:
4
解题思路:
- 先建立以1节点为根的多叉树, 实际将编码中将编号全部减1,从0开始编号,将树看成图使用邻接表存储。
- 计算根节点得子节点为根的子树节点数量,最大节点数量为答案。采用层次遍历,并标记已经访问的节点。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Integer>[] g = new ArrayList[n];
for(int i=0; i < n-1; i++) {
int x = sc.nextInt(), y = sc.nextInt();
if(g[x-1] == null) g[x-1] = new ArrayList<>();
if(g[y-1] == null) g[y-1] = new ArrayList<>();
g[x-1].add(y-1);
g[y-1].add(x-1);
}
int res = 0;
for(int k=0; k < g[0].size(); k++) {
int root = g[0].get(k);
boolean[] st = new boolean[n];
Queue<Integer> q = new LinkedList<>();
q.offer(root); st[root] = true; st[0] = true;
int ans = 0;
while(!q.isEmpty()) {
int size = q.size();
for(int i = 0; i < size; i++) {
int cur = q.poll();ans++;
for(int j=0; j < g[cur].size(); j++) {
int node = g[cur].get(j);
if(st[node] != true) {
q.offer(node);
st[node] = true;
}
}
}
}
if(ans > res) res = ans;
}
System.out.println(res);
}
}