牛客网 2018校招真题 美团点评 公交车

Description

牛客网 2018校招真题 公交车

Solving Ideas

建图:
将公交车抽象成一个站点,将公交车与其可达站点的关系作为无向图的边,边集只记录公交车与站点的关系。

求最小花费:
从起点开始使用bfs算法求最短距离,因为设立了抽象点,起点距离又设为1,所以每个点的距离是实际距离的两倍加一,例如
在这里插入图片描述
起点为1,n = 5,由bfs得dist[n] = 5,但实际花费为2

Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author wylu
 */
public class Main {
    static ArrayList<Integer>[] graph;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] strs = br.readLine().split(" ");
        int n = Integer.parseInt(strs[0]), m = Integer.parseInt(strs[1]);
        graph = new ArrayList[n + m + 1];

        //建图, 将公交车抽象成一个站点, 只记录公交车可到站点的边
        for (int i = 1; i <= m; i++) {
            strs = br.readLine().split(" ");
            graph[i + n] = new ArrayList<>();
            for (int j = 1; j < strs.length; j++) {
                int station = Integer.parseInt(strs[j]);
                if (graph[station] == null) graph[station] = new ArrayList<>();
                graph[station].add(i + n);
                graph[i + n].add(station);
            }
        }

        //bfs求最短路, 
        int res = bfs(1, n, m);
        //因为设立了抽象点,起点距离又设为1,所以每个点的距离是实际距离的两倍加一
        System.out.println(res == 0 ? "-1" : res / 2);
    }

    private static int bfs(int x, int n, int m) {
        int[] dist = new int[n + m + 1];
        LinkedList<Integer> queue = new LinkedList<>();
        dist[x] = 1;
        queue.offer(x);
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            for (Integer e : graph[cur]) {
                if (dist[e] == 0) {
                    dist[e] = dist[cur] + 1;
                    queue.offer(e);
                }
            }
        }
        return dist[n];
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值