ZOJ-2913

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();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值