CodeForces - 982C Cut ‘em all! 无向图 遍历dfs

Training 5 - H题

You’re given a tree with nn vertices.
Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.

Input

The first line contains an integer nn (1≤n≤1051≤n≤105) denoting the size of the tree.
The next n−1n−1 lines contain two integers uu, vv (1≤u,v≤n1≤u,v≤n) each, describing the vertices connected by the ii-th edge.
It’s guaranteed that the given edges form a tree.

Output

Output a single integer kk — the maximum number of edges that can be removed to leave all connected components with even size, or −1−1 if it is impossible to remove edges in order to satisfy this property.

Examples

Input

4
2 4
4 1
3 1

Output

1

Input

3
1 2
1 3

Output

-1

Input

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

Output

4

Input

2
1 2

Output

0

Note

In the first example you can remove the edge between vertices 11 and 44. The graph after that will have two connected components with two vertices in each.
In the second example you can’t remove edges in such a way that all components have even number of vertices, so the answer is −1−1.

#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e7 + 5;
const int maxn = 2e5 + 5;

int head[maxn], ver[maxn], nex[maxn];
int s[maxn];//子节点数
bool v[maxn];
int tot = 0;

void add(int x, int y)
{
	++tot;
	ver[tot] = y;
	nex[tot] = head[x];
	head[x] = tot;
}

void dfs(int x)
{
	v[x] = 1;
	s[x]++;
	for (int i = head[x]; i; i = nex[i])
	{
		if (v[ver[i]])
			continue;
		dfs(ver[i]);
		s[x] += s[ver[i]];
	}
}

int main()
{
	int n;
	int ans = 0;
	scanf("%d", &n);
	for (int i = 2; i <= n; i++)
	{
		int u, v;
		scanf("%d%d", &u, &v);
		add(u, v);
		add(v, u);
	}
	dfs(1);
	if (n % 2 == 1)
		printf("-1\n");
	else
	{
		for (int i = 1; i <= n; i++)
			if (s[i] % 2 == 0)
				ans++;
		printf("%d\n", ans - 1);
	}
	return 0;
}

思路:
遍历一边,储存每个节点的子节点个数。如果该节点为根节点的子树的节点个数是偶数,就可以把这个子树分开。
用无向图存储,dfs遍历。
注意:要减去根节点的次数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值