百度Java笔试编程题第3题

有老哥a了第二题吗,瞪了半个小时愣是不知道怎么做。
第三题是给一棵树(实际就是无向图,但是无环),每个节点有值,要求找出最长严格递增路径的长度。

public class Main {
    public static class Node {
        public int val;
        public int maxLoop = -1;
        public List<Integer> next = new ArrayList<Integer>();
        public Node(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) {
        // 获取输入
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Node[] nodes = new Node[n + 1];
        for (int i = 1; i <= n; ++i) {
            nodes[i] = new Node(scanner.nextInt());
        }
        for (int i = 0; i < n - 1; ++i) {
            int u = scanner.nextInt();
            int v = scanner.nextInt();
            if (nodes[u].next == null) {
                nodes[u].next = new ArrayList<Integer>();
            }
            if (nodes[v].next == null) {
                nodes[v].next = new ArrayList<Integer>();
            }
            nodes[u].next.add(v);
            nodes[v].next.add(u);
        }

        // dfs
        int result = 1;
        for (int i = 1; i <= n; ++i) {
            int ret = dfs(nodes, i);
            result = result > ret ? result : ret;
        }
        System.out.println(result);
    }

    public static int dfs(Node[] nodes, int i) {
        if (nodes[i].maxLoop != -1) {
            return nodes[i].maxLoop;
        }
        int result = 0;
        for (int nextIndex : nodes[i].next) {
            if (nodes[nextIndex].val > nodes[i].val) {
                int ret = dfs(nodes, nextIndex);
                result = result > ret ? result : ret;
            }
        }
        nodes[i].maxLoop = result + 1;
        return result + 1;
    }
}
#百度##笔试题目##Java工程师#
全部评论

相关推荐

allin秋招的大菠萝很爱交友:后续,已拿offer ~查看图片
点赞 评论 收藏
分享
评论
1
2
分享

创作者周榜

更多
牛客网
牛客企业服务