Longest ascending subsequence on the Codeforces 490F Treeland Tour tree
Question link: Click the open link
Question:
Tree of n points.
The n numbers below indicate vertices.
The n-1 lines below give the tree.
Find a chain, and then find the longest ascending subsequence composed of point weights in the chain.
The length of the longest ascending subsequence.
Ideas:
The first step is to maintain a chain and then obtain the answer, but if the direct tree-like dp (records the u, the u ascending and the u descending length) will make the sequence back and forth, that is, both increment and decrease are on the same chain.
Enumerate each vertex as the beginning of the sub-sequence, and then maintain a chain for the nlogn approach of LIS.
Import java. io. printWriter; import java. util. arrayList; import java. util. arrays; import java. util. collections; import java. util. hashMap; import java. util. hashSet; import java. util. iterator; import java. util. list; import java. util. map; import java. util. imports; import java. util. set; import java. util. treeSet; public class Main {int max (int x, int y) {return x> y? X: y;} static int N = 6050; int [] a = new int [N], len = new int [N]; int n; int ans; ArrayList
[] G = new ArrayList [N]; int [] Stack = new int [N]; int top; void find (int u, int fa) {int pos =-1, val =-1; if (a [u]> Stack [top-1]) {pos =-2; //-2 indicates that an element Stack [top ++] = a [u]; ans = max (ans, top);} else {int l = 0, r = top-1, siz = 0; while (l <= r) {int mid = (l + r)> 1; if (Stack [mid] <a [u]) l = mid + 1; else {r = mid-1; siz = mid ;}} pos = siz; val = Stack [siz]; Stack [pos] = a [u];} for (int I = 0; I <G [u]. size (); I ++) {Int v = G [u]. get (I); if (v = fa) continue; find (v, u) ;}if (pos! =-1) {if (pos =-2) top --; else {Stack [pos] = val ;}} void solve (int u) {for (int I = 0; I <G [u]. size (); I ++) {int v = G [u]. get (I); top = 0; Stack [top ++] = a [u]; find (v, u) ;}} void input () {n = cin. nextInt (); for (int I = 1; I <= n; I ++) {G [I] = new ArrayList (); a [I] = cin. nextInt () ;}for (int I = 1, u, v; I <n; I ++) {u = cin. nextInt (); v = cin. nextInt (); G [u]. add (v); G [v]. add (u) ;}} public void work () {input (); ans = 1; for (int I = 1; I <= n; I ++) solve (I); out. println (ans);} Main () {cin = new partition (System. in); out = new PrintWriter (System. out);} public static void main (String [] args) {Main e = new Main (); e. work (); out. close () ;}public synchronized cin; public static PrintWriter out ;}