首页 > 其他 > 详细

公交车, 美团笔试题

时间:2020-07-01 13:26:52      阅读:58      评论:0      收藏:0      [点我收藏+]

原来有n个公交车站,有m条公交线路。对于其中一条线路a->b->c,使得a,b,c三个公交车站距离变成了1(1块钱可以到达)。因此,我们建立无向图(边全值为1)。但是公交线路长度很长(2<=t <=100000),这样对一个公交线路来说,建边复杂度为\(10^5 \times 10^5\)。为了降低复杂度,每个线路都建立一个虚拟节点,使得公交车站通过虚拟节点相连接,这样就减少了边的数量,这样对一个公交线路来说,建边复杂度为\(10^5\)。对于对于其中一条线路a->b->c, 建立一个节点x,如果要求a到b的距离,a,b之间并没有直接边相连,而是通过x节点,间接相连(a->x->b)。因此,我们将边的权值设为0.5,a到b的权值就仍然为1。问题还是求1-n的距离。

import java.util.*;
public class Main {
    static int bfs(List<Integer>[] g, int n){
        boolean[] used = new boolean[g.length];
        LinkedList<Integer> q = new LinkedList<>();
        q.offer(1); used[1] = true;
        int distance = 0;
        while(!q.isEmpty()){
            int size = q.size();
            distance ++;
            for(int i=0; i < size; i++) {
                int cur = q.poll();
                for(int j=0; j <g[cur].size(); j++) {
                    int v = g[cur].get(j);
                    if(v == n) return distance/2;
                    if(used[v] == false) {
                        used[v] = true;
                        q.offer(v);
                    }
                }
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), m = sc.nextInt();
        List[] g = new ArrayList[n+m+1];
        for(int i=1; i < g.length; i++) g[i] = new ArrayList<Integer>();
        for(int i=1; i <= m; i++) {
            int t = sc.nextInt();
            for(int j=1; j <= t; j++) {
                int v = sc.nextInt();
                g[n+i].add(v);
                g[v].add(n+i);
            }
        }
        int res = bfs(g, n);
        System.out.println(res);
    }
}

公交车, 美团笔试题

原文:https://www.cnblogs.com/lixyuan/p/13218568.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!