输入样例:
13
3 2 3 4
2 5 6
1 7
1 8
1 9
0
2 11 10
1 13
0
0
1 12
0
0
输出样例:
12
解题思路:
找最大深度的编号,由于答案唯一,所以宽搜到的最后一个结点就是bfs扩展最远的点;也可以深搜,通过递归左右儿子更新最大深度时更新结点编号,但dfs有两个点没过,找不出原因。
Java代码:
import java.io.*;
import java.util.*;
public class Main {
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static int ini() throws IOException {
st.nextToken();
return (int)st.nval;
}
static int N = 100005, n, idx, maxd, maxid;
static int[]e = new int[N];
static int[]ne = new int[N];
static int[]h = new int[N];
static boolean[]vis = new boolean[N];
public static void main(String[] args) throws IOException {
n = ini();
Arrays.fill(h, -1);
for(int i = 1; i <= n; i++) {
int m = ini();
for(int j = 0; j < m; j++) {
int t = ini();
vis[t] = true;
add(i, t);
}
}
for(int i = 1; i <= n; i++)
if(!vis[i])
// bfs(i); // 调用宽搜
dfs(i, 1); // 调用深搜
System.out.println(maxid);
}
public static void dfs(int u, int deep) {
if(deep > maxd) {
maxd = deep;
maxid = u;
}
for(int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
dfs(j, deep + 1);
}
}
public static void bfs(int root) {
Queue<Integer> qu = new LinkedList<>();
qu.add(root);
int t = 0;
while(!qu.isEmpty()) {
t = qu.poll();
for(int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
qu.add(j);
}
}
System.out.println(t);
}
public static void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}
dfs:
bfs