Obtain forest out of tree with even number of nodes

后端 未结 8 496
别跟我提以往
别跟我提以往 2021-02-03 20:31

I\'m stuck on a code challenge, and I want a hint.

PROBLEM: You are given a tree data structure (without cycles) and are asked to remo

相关标签:
8条回答
  • 2021-02-03 21:21

    Here's the general outline of an alternative approach:

    1. Find all of the articulation points in the graph.
    2. Check each articulation point to see if edges can be removed there.
    3. Remove legal edges and look for more articulation points.
    0 讨论(0)
  • 2021-02-03 21:36

    This is my solution. I didn't use bfs tree, just allocated another array for holding eachnode's and their children nodes total number.

    import java.util.Scanner;
    import java.util.Arrays;
    
    public class Solution {
            public static void main(String[] args) {
                    int tree[];
                    int count[];
    
                    Scanner scan = new Scanner(System.in);
    
                    int N = scan.nextInt(); //points
                    int M = scan.nextInt();
    
                    tree = new int[N];
                    count = new int[N];
                    Arrays.fill(count, 1);
    
                    for(int i=0;i<M;i++)
                    {
                            int u1 = scan.nextInt();
                        int v1 = scan.nextInt();
    
                        tree[u1-1] = v1;
    
                        count[v1-1] += count[u1-1];
    
                        int root = tree[v1-1];
    
                        while(root!=0)
                        {
                            count[root-1] += count[u1-1];
                            root = tree[root-1];
                        }
                    }
    
                    System.out.println("");
    
                    int counter = -1;
                    for(int i=0;i<count.length;i++)
                    {
                            if(count[i]%2==0)
                            {
                                    counter++;
                            }
    
                    }
                    System.out.println(counter);
    
            }
    
    }
    
    0 讨论(0)
提交回复
热议问题