BFS搜索,数据题挺大,用JAVA看着那近20M内存使用,真心寒啊,不会C++ STL就是那么惨。。写的过程一直在担心内存会不会爆掉,每new一个map出来就感觉内存要超了。。如履薄冰啊,第一次写完提交TLE了。。内存使用20M多了,后来搜了搜别人的思路再思考了下,发现可以在BFS的时候就可以更新每个点的最大最短距离了,不用到最后才一起处理,把最后的代码删掉然后重写BFS后就过了。。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Main
{
static Map<Integer, ArrayList<Integer>> adj = new HashMap<Integer, ArrayList<Integer>>();
static Set<Integer> dest = new HashSet<Integer>();
static Map<Integer, Boolean> visit = new HashMap<Integer, Boolean>();
static Map<Integer, Integer> mind = new HashMap<Integer, Integer>();
static Map<Integer, Integer> res = new HashMap<Integer, Integer>();
static void bfs(int id)
{
for (int key : visit.keySet())
visit.put(key, false);
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.addLast(id);
res.put(id, 1);
visit.put(id, true);
while (!queue.isEmpty())
{
int now = queue.removeFirst();
int d = res.get(now);
if (mind.get(now) < d)
mind.put(now, d);
if (adj.containsKey(now))
{
List<Integer> list = adj.get(now);
for (int num : list)
{
if (!visit.get(num))
{
visit.put(num, true);
res.put(num, d + 1);
queue.addLast(num);
}
}
}
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0)
{
adj.clear();
dest.clear();
visit.clear();
mind.clear();
int nz = sc.nextInt();
int nr = sc.nextInt();
while (nz-- > 0)
{
int id = sc.nextInt();
if (!adj.containsKey(id))
adj.put(id, new ArrayList<Integer>());
visit.put(id, false);
mind.put(id, 0);
ArrayList<Integer> list = adj.get(id);
int mz = sc.nextInt();
while (mz-- > 0)
list.add(sc.nextInt());
}
while (nr-- > 0)
{
int num = sc.nextInt();
while (num-- > 0)
dest.add(sc.nextInt());
}
for (int key : dest)
bfs(key);
int cc = Integer.MAX_VALUE, min = Integer.MAX_VALUE;
for (int city : mind.keySet())
{
int d = mind.get(city);
if (d < min || (d == min && city < cc))
{
min = d;
cc = city;
}
}
System.out.println(min + " " + cc);
}
sc.close();
}
}