首页 > 试题广场 >

树上上升序列

[编程题]树上上升序列
  • 热度指数:1485 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
度度熊给定一棵树,树上的第个节点有点权。请你找出一条最长的路径,使得从沿着唯一路径走到的途中,点权不断严格递增。
换句话说,设路径为,则需要满足。输出最长满足条件的路径的长度。

输入描述:
第一行树的节点个数 , 接下来一行个数字,表示每个点的点权。接下来行,每行两个数代表树上的一条边,连接点
.


输出描述:
一行一个数字表示答案,即最长的长度。
示例1

输入

5
3 5 5 4 1
1 2
1 3
2 4
2 5

输出

2
示例2

输入

4
3 4 1 2
1 2
2 3
2 4

输出

2


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Main solution = new Main();
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        int[] weight = new int[n];
        for (int i = 0; i < n; i++) {
            weight[i] = scanner.nextInt();
        }
        ArrayList<Integer>[] lists = new ArrayList[n + 1];
        for (int i = 0; i < lists.length; i++) {
            lists[i] = new ArrayList<>();
        }
        for (int i = 0; i < n - 1; i++) {
            int u = scanner.nextInt();
            int v = scanner.nextInt();
            lists[u].add(v);
            lists[v].add(u);
        }

        int res = solution.solve(lists, weight);
        System.out.println(res);

    }


    static ArrayList<Integer> maxLen = new ArrayList<>();
    private int solve(ArrayList<Integer>[] lists, int[] weight) {

        LinkedList<Integer> path = new LinkedList<>();

        for (int i = 1; i < lists.length; i++) {
            path.add(i);
            loopBack(lists, weight, path, i);
            path.removeLast();
        }

        return maxLen.size();
    }

    private void loopBack(ArrayList<Integer>[] lists, int[] weight, LinkedList<Integer> path, int index) {

        if (maxLen.size() < path.size()) {
            maxLen = new ArrayList<>(path);
        }

        int curWeight = weight[index - 1];
        for (Integer integer : lists[index]) {
            if (weight[integer - 1] > curWeight) {
                path.add(integer);
                loopBack(lists, weight, path, integer);
                path.removeLast();
            }
        }
    }
}

发表于 2021-11-13 10:42:46 回复(0)