Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- public class NutrientTree {
- static Node createTree(String s) {
- s = s.trim();
- if(s.charAt(0) != '(') {
- return new Node(Integer.parseInt(s));
- }else {
- s = s.substring(1, s.length() - 1).trim();
- int ind = -1;
- if(s.charAt(0) != '(') {
- ind = s.indexOf(' ');
- }else {
- int count = 0;
- for(int i = 0; i < s.length(); i ++) {
- if(s.charAt(i) == '(') {
- count ++;
- }else if(s.charAt(i) == ')') {
- count --;
- }
- if(count == 0) {
- ind = i;
- break;
- }
- }
- }
- return new Node(createTree(s.substring(0, ind + 1)), createTree(s.substring(ind + 1)));
- }
- }
- static void solve(Node tree, int x) {
- if(tree.lc == null) {
- tree.dp = new int[x + 1];
- for(int i = 0; i <= x; i ++) {
- tree.dp[i] = tree.v + i;
- }
- }else {
- solve(tree.lc, x);
- solve(tree.rc, x);
- int[] dpl = new int[x + 1];
- for(int i = 0; i <= x; i ++) {
- int max = 0;
- for(int j = 0; j <= i; j ++) {
- max = Math.max(Math.min((1 + j) * (1 + j), tree.lc.dp[i - j]), max);
- }
- dpl[i] = max;
- }
- int[] dpr = new int[x + 1];
- for(int i = 0; i <= x; i ++) {
- int max = 0;
- for(int j = 0; j <= i; j ++) {
- max = Math.max(Math.min((1 + j) * (1 + j), tree.rc.dp[i - j]), max);
- }
- dpr[i] = max;
- }
- tree.dp = new int[x + 1];
- for(int i = 0; i <= x; i ++) {
- int max = 0;
- for(int j = 0; j <= i; j ++) {
- max = Math.max(dpl[j] + dpr[i - j], max);
- }
- tree.dp[i] = max;
- }
- }
- }
- public static void main(String[] args) throws IOException{
- String s = in.readLine();
- readLine();
- int x = nextInt();
- Node root = createTree(s);
- solve(root, x);
- System.out.println(root.dp[x]);
- }
- static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- static StringTokenizer st;
- static void readLine() throws IOException{
- st = new StringTokenizer(in.readLine());
- }
- static int nextInt() {
- return Integer.parseInt(st.nextToken());
- }
- static class Node{
- int[] dp;
- int v;
- Node lc, rc;
- Node(int v){
- this.v = v;
- lc = null;
- rc = null;
- }
- Node(Node lc, Node rc){
- v = 0;
- this.lc = lc;
- this.rc = rc;
- }
- void print() {
- if(lc == null) {
- System.out.println(v);
- }else {
- System.out.println("this is node");
- lc.print();
- rc.print();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment