HackerRank - even-tree(dfs/并查集

even-tree(dfs/并查集

Description

You are given a tree (a simple connected graph with no cycles). The tree has nodes numbered from to and is rooted at node .

Find the maximum number of edges you can remove from the tree to get a forest such that each connected component of the forest contains an even number of vertices.

Input

The first line of input contains two integers and . is the number of vertices, and is the number of edges.
The next lines contain two integers and which specifies an edge of the tree.
Constraints
2<= N <= 100
Note: The tree in the input will be such that it can always be decomposed into components containing an even number of nodes.

Output

Print the number of removed edges.

Sample Input

10 9
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
10 8

Sample Output

2

Hint

样例中移除掉(1,3)(1,6)两条边满足条件。
原始树:
这里写图片描述
分解的树:
这里写图片描述

题意

给你一棵有n个节点的树(一个无环简单图),节点序号为1~n,根节点为1。
请你找出一个最大的整数k,表示从这棵树上断掉k条边使其所有的子树的节点数都为偶数。

题解:

随便搜搜就过了 sad看错题了 没敢写 (并查集方法懒得写了 有空在补吧

AC代码

#include <bits/stdc++.h>
using namespace std;

const int N = 110;
int mps[N][N], par[N], siz[N];
int n, m, cnt = 0;
int dfs(int a,int b)
{
    par[a] = b;
    mps[a][b] = 0;
    siz[a] = 1;
    for(int i = 1;i <= n; i++) {
        if(mps[a][i]) {
            int k = dfs(i,a);
            if(k%2==0) cnt++;
            siz[a] += k;
        }
    }
    return siz[a];
}
int main()
{
    int a, b;
    memset(mps,0,sizeof(mps));
    cin>>n>>m;
    for(int i = 0;i < m; i++) {
        cin>>a>>b;
        mps[a][b] = mps[b][a] = 1;
    }
    dfs(1,1);
    cout<<cnt<<endl;

return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值