题目:
You're given a tree with nvertices.
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.
输入:
The first line contains an integer n (1≤n≤105) denoting the size of the tree.
The next n−1lines contain two integers u, v (1≤u,v≤n) each, describing the vertices connected by the i-th edge.
It's guaranteed that the given edges form a tree.
输出:
Output a single integer k — the maximum number of edges that can be removed to leave all connected components with even size, or −1 if it is impossible to remove edges in order to satisfy this property.
样例输入:
4 2 4 4 1 3 1
3 1 2 1 3
10 7 1 8 4 8 10 4 7 6 5 9 3 3 5 2 10 2 5
2 1 2
输出:
1
-1
4
0
Note:
In the first example you can remove the edge between vertices 1 and 4.
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
题意:给一棵树有n个顶点,问最多能去掉多少条边使得每一个连通块都有偶数个顶点。
如果n是奇数,奇数=奇数+偶数,所以肯定不能保证所有的连通块都是偶数个顶点,输出-1.
n是偶数的时候,进行dfs,对于这棵树,如果一个结点的子树已经是偶数个顶点了,直接砍掉;如果是奇数,就把这个“奇数”加到当前顶点上。
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn=200005;
struct node//建立邻接表
{
int y,next;
}Node[maxn];
int cnt;
int ans=0;//砍掉的边的条数
int head[maxn];
int vis[maxn];
int sum[maxn];
void add(int x,int y)
{
Node[cnt].y=y;
Node[cnt].next=head[x];
head[x]=cnt++;
}
int dfs(int x)
{
vis[x]=1;//已经遍历过的标记一下
for(int i=head[x];i!=-1;i=Node[i].next)
{
int v=Node[i].y;//与起点x相连的点
if(!vis[v])
{
int a=dfs(v);//接着以这个点为起点进行遍历
if(a%2==1)//这个这个子树的结点为奇数,就加到当前结点上
sum[x]+=a;
else
ans++;//否则直接砍掉
}
}
return sum[x]+1;//返回的是这个结点及其子树的所有顶点数
}
int main()
{
int n;
cnt=0;
scanf("%d",&n);
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
for(int i=0;i<n-1;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v);//建立双向边
add(v,u);
}
if(n%2==1)
{
printf("-1\n");
return 0;
}
dfs(1);//从顶点1开始遍历
printf("%d\n",ans);
return 0;
}