搜索
java算法
PHP中文网
PHP中文网 2017-04-17 14:33:19
[Java讨论组]
PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
黄舟

BSF:

private static class Pair{
    char c;
    int duration;

    public Pair(char c, int duration) {
        this.c = c;
        this.duration = duration;
    }
}

public int search(String[] input){
    Map<Character, Set<Pair>> map = new HashMap<>();
    for(String s: input){
        char c1 = s.charAt(0), c2 = s.charAt(1);
        int duration = s.charAt(2) - '0';
        if(!map.containsKey(c1))
            map.put(c1, new HashSet<>());
        map.get(c1).add(new Pair(c2, duration));
    }

    int count = 0;
    Queue<Pair> q = new LinkedList<Pair>();
    q.offer(new Pair('C', 0));
    while(!q.isEmpty()){
        int size = q.size();
        while(size-- > 0){
            Pair cur = q.poll();
            for(Pair p: map.get(cur.c)){
                if(cur.duration + p.duration >= 30)
                    continue;
                if(p.c == 'C')
                    count++;
                q.offer(new Pair(p.c, cur.duration + p.duration));
            }
        }
    }
    return count;
}

@Test
public void test(){
    assertEquals(7, search(new String[]{"AB5", "BC4", "CD8", "DC8", "DE6", 
            "AD5", "CE2", "EB3", "AE7"}));
}
伊谢尔伦

题目没有给出数据范围,如果数据比较小的话,在每个点上挂一张表,表示从C到该点有哪些路径长度可行,然后从C开始做一遍BFS即可,最后统计C点上表的大小即可。如果数据比较大可以考虑Tarjan缩环啥的……

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号