📜  在给定的 N 数组树中查找最大独立集 (LIS) 大小的Java程序

📅  最后修改于: 2021-09-07 02:44:21             🧑  作者: Mango

1. 如果节点为空，这意味着该节点不存在，那么我们不能包含任何内容。
2. 如果节点是叶子，那么我们必须包含它。

Java
``````// Java Program to Find Size of the Largest Independent
// Set(LIS) in a Given an N-array Tree
import java.io.*;
import java.util.*;

// save the file named as GFG2.java
public class GFG2 {

// declaring static list of vector.
public static Vector > v
= new Vector >();

// 7 nodes initially
public static int n = 7;
public static void main(String[] args)
{
System.out.println("Initializing an n array tree");

Vector v0 = new Vector();
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
Vector v4 = new Vector();

/*
the tree looks like
0
/        \
1        2
/\       /
3  4      5
/
6
so initially the vector looks like
v = {
{1,2},
{3,4},
{5},
{6},
{},
{},
{},
}
*/

System.out.println(
"Finding the elements to be included in the set");

// calling the function wihe the first node.
int x = LIS(0);
System.out.println("process finished and size is "
+ x);
}

public static int LIS(int a)
{
// if no node is there with labelling a
if (a >= n)
return 0;

// if it is leaf node
if (v.get(a).size() == 0) {
System.out.println(a);
return 1;
}
// if not considering that node
int ifno = 0;

// if considering that node.
int ifyes = 1;

// since not considering this node
// so we should call the same function
// on the children of this node
for (int i = 0; i < v.get(a).size(); ++i)
ifno += LIS(v.get(a).get(i));

// if including this node
// then call the same function recursivelly on the
// grand children of this node.
for (int i = 0; i < v.get(a).size(); ++i) {
int k = v.get(v.get(a).get(i)).size();
--k;
while (k >= 0) {
ifyes += LIS(v.get(v.get(a).get(i)).get(k));
--k;
}
}

// if found that including this node is beneficial
if (ifyes > ifno)
System.out.println(a);
return Math.max(ifyes, ifno);
}
}``````

``````Initializing an n array tree
Finding the elements to be included in the set
6
4
6
5
4
6
5
0
process finished and size is 4``````