C. Cut ‘em all!
time limit per test : 1 second
memory limit per test : 256 megabytes
You’re given a tree with
n
n
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 denoting the size of the tree.
The next n−1 n − 1 lines contain two integers u,v(1≤u,v≤n) u , v ( 1 ≤ u , v ≤ n ) each, describing the vertices connected by the i i -th edge.
It’s guaranteed that the given edges form a tree.
Output
Output a single integer — 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
Input1
4
2 4
4 1
3 1
Output1
1
Input2
3
1 2
1 3
Output2
-1
Input3
10
7 1
8 4
8 10
4 7
6 5
9 3
3 5
2 10
2 5
Output3
4
Input4
2
1 2
Output4
0
Note
In the first example you can remove the edge between vertices 1 1 and . 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
.
题意:
给一棵n个点的树,删去其中的k条边,使得所有剩余的联通块的大小都为偶数。求k的最大值。如果无法实现每个联通块的大小都为偶数则输出 −1 − 1
题解:
显然,如果n为奇数则直接输出 −1 − 1 ,我们从任意一个点开始dfs,dfs到第i个点的时候,如果该点的子树大小为偶数,则该点不和自己的父亲节点连边,cnt+0; 否则和父亲连边,cnt+1。最终答案为cnt-1。
#include<bits/stdc++.h>
#define LiangJiaJun main
using namespace std;
struct edge{
int to , nt;
}e[250004];
int ne,h[100004],n,ans;
bool vis[100004];
void add(int u,int v){
e[++ne].to=v;e[ne].nt=h[u];
h[u]=ne;
}
int dfs(int x){
vis[x]=1;
int ret=0;
for(int i=h[x];i;i=e[i].nt){
if(!vis[e[i].to])ret+=dfs(e[i].to);
}
ans+=ret%2;
return ret+1;
}
int w33ha(){
ne=0;ans=-1;
memset(h,0,sizeof(h));
memset(vis,0,sizeof(vis));
for(int i=1;i<n;i++){
int u,v;
scanf("%d%d",&u,&v);
add(u,v);add(v,u);
}
if(n&1)return puts("-1"),0;
dfs(1);
printf("%d\n",ans);
return 0;
}
int LiangJiaJun(){
while(scanf("%d",&n)!=EOF)w33ha();
return 0;
}