What is a good algorithm for getting the minimum vertex cover of a tree?

后端 未结 7 681
感动是毒
感动是毒 2020-12-28 16:55

What is a good algorithm for getting the minimum vertex cover of a tree?

INPUT:

The node\'s neighbours.

OUTPUT:

The minimum number of vertice

7条回答
  •  一个人的身影
    2020-12-28 17:13

    We need to find the minimum vertex cover for each node we have to choices to make, either to include it or not to include it. But according to the problem for each edge (u, v), either of 'u' or 'v' should be in the cover so we need to take care that if the current vertex is not included then we should include its children, and if we are including the current vertex then, we may or may not include its children based on optimal solution.

    Here, DP1[v] for any vertex v = When we include it. DP2[v] for any vertex v = when we don't include it.

    DP1[v] = 1 + sum(min(DP2[c], DP1[c])) - this means include current and may or may not include its children, based on what is optimal.

    DP2[v] = sum(DP1[c]) - this means not including current then we need to include children of current vertex. Here, c is the child of vertex v.

    Then, our solution is min(DP1[root], DP2[root])

    #include 
    using namespace std;
    
    vector > g;
    
    int dp1[100010], dp2[100010];
    
    void dfs(int curr, int p){
        for(auto it : g[curr]){
            if(it == p){
                continue;
            }
            dfs(it, curr);
            dp1[curr] += min(dp1[it], dp2[it]);
            dp2[curr] += dp1[it];
        }
        dp1[curr] += 1;
    }
    
    int main(){
        int n;
        cin >> n;
        g.resize(n+1);
        for(int i=0 ; i> u >> v;
            g[u].push_back(v);
            g[v].push_back(u);
        }
        dfs(1, 0);
        cout << min(dp1[1], dp2[1]);
        return 0;
    } 
    

提交回复
热议问题