L2-031 深入虎穴 - java

L2-031 深入虎穴


时间限制
400 ms
内存限制
64 MB


题目描述:

著名的王牌间谍 007 需要执行一次任务,获取敌方的机密情报。已知情报藏在一个地下迷宫里,迷宫只有一个入口,里面有很多条通路,每条路通向一扇门。每一扇门背后或者是一个房间,或者又有很多条路,同样是每条路通向一扇门…… 他的手里有一张表格,是其他间谍帮他收集到的情报,他们记下了每扇门的编号,以及这扇门背后的每一条通路所到达的门的编号。007 发现不存在两条路通向同一扇门。

内线告诉他,情报就藏在迷宫的最深处。但是这个迷宫太大了,他需要你的帮助 —— 请编程帮他找出距离入口最远的那扇门。

输入格式:
输入首先在一行中给出正整数 N(< 1 0 5 10^{5} 105),是门的数量。最后 N 行,第 i 行(1≤i≤N)按以下格式描述编号为 i 的那扇门背后能通向的门:
K D[1] D[2] … D[K]
其中 K 是通道的数量,其后是每扇门的编号。

输出格式:
在一行中输出距离入口最远的那扇门的编号。题目保证这样的结果是唯一的。

输入样例:
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


给定每扇门后能通先的门

求出离入口最远的一扇门的距离


emmmmmmm

bfs搜索当前这扇门能到达的门 记录距离

从入口开始去找 最远的一扇门

因为不存在两条路通向同一扇门 所以如果的入点为0


import java.io.*;
import java.math.*;
import java.util.*;

public class Main
{
	static int N = (int) 1e5, M = N << 1;
	static int h[] = new int[N + 10], shu[] = new int[M + 10], ne[] = new int[M + 10], idx;
	static int d[] = new int[N + 10];
	static boolean user[] = new boolean[N + 10];

	static void add(int a, int b)
	{
		shu[idx] = b;
		ne[idx] = h[a];
		h[a] = idx++;
	}

	static void bfs(int root)
	{
		LinkedList<Integer> li = new LinkedList<Integer>();
		li.add(root);
		d[root] = 1;

		int max = 0;
		int end = 0;
		while (li.size() != 0)
		{
			int u = li.poll();
			if (d[u] > max)
			{
				end = u;
				max = d[u];
			}

			for (int i = h[u]; i != 0; i = ne[i])
			{
				int j = shu[i];
				if (d[j] == 0)
				{
					d[j] = d[u] + 1;
					li.push(j);
				}
			}
		}
		out.println(end);
	}

	public static void main(String[] args) throws IOException
	{
		int n = ini();

		idx = 1;
		for (int i = 1; i <= n; i++)
		{
			int m = ini();
			while (m-- > 0)
			{
				int x = ini();
				add(i, x);
				user[x] = true;
			}
		}

		int root = 1;
		while (user[root])
			root++;

		bfs(root);

		out.flush();
		out.close();
	}

	static StreamTokenizer sc = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
	static PrintWriter out = new PrintWriter(System.out);

	static int ini() throws IOException
	{
		sc.nextToken();
		return (int) sc.nval;
	}
}

bfs

LinkedList


如果有说错的 或者 不懂的 尽管提 嘻嘻

一起进步!!!


闪现

你可能感兴趣的:(pta,学习)