View Code of Problem 3858

import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner in =new Scanner(System.in);
		int t =in.nextInt();
		for(int i =0;i<t;i++) {
			int n =in.nextInt();
			int m =in.nextInt();
			int[][] tree  =new int[n][n];
			int[] city  =new int[n];
			for(int j =1;j<n;j++) {
				int father= in.nextInt()-1;
				tree[father][j]=1;
				tree[j][father]=1;
			}
			int[] p =new int[n];
			int[] q =new int[n];
			for(int j =0;j<n;j++) {
				p[j]=in.nextInt();
				q[j]=in.nextInt();
			}
			for(int j =0;j<m;j++) {
				int x=in.nextInt()-1;
				System.out.println(light(tree,city,p,q,x));
			}
		}
	}
	public static int light(int[][] tree,int[] city,int[] p,int[] q,int loc) {
		city[loc]=1;
		if(loc==0) {
			int maxb=Integer.MIN_VALUE;
			for(int j =0;j<city.length;j++) {
				for(int l =0;l<city.length;l++) {
					if(l!=j && city[j]==1 && city[l]==1) {
						int beauty=p[l]*p[j]+q[l]*q[j];
						if(maxb<beauty) {
							maxb=beauty;
						}
					}
				}
			}
			return maxb;
		}else {
			int max = Integer.MIN_VALUE;
			for(int i =0;i<tree[loc].length;i++) {
				if(tree[loc][i]!=0 && city[i]==0) {
					city[i]=1;
					int b =light(tree,city,p,q,i);
					city[i]=0;
					if(max<b) {
						max=b;
					}
				}
			}
			city[loc]=0;
			return max;
		}
	}
}

Double click to view unformatted code.


Back to problem 3858