B - Cut
Time Limit:
4000/2000MS (Java/Others)
Memory Limit:
128000/64000KB (Java/Others)
Problem Description
Cut(in another word, remove) edges the given tree \(T\) so that each connected component has even number of nodes.
Find out the maximum number of removed edges.
Input
The first line contains one integer \(n\), which denotes the number of nodes of tree \(T\).
The following \((n - 1)\) lines with two integers \(a_i, b_i\), which denotes edge \((a_i, b_i)\).
Note that the nodes are labled by \(1, 2, \ldots, n\).
(\(1 \leq n \leq 10^5\), \(n\) is even)
Output
The only integer shows the maximum number of removed edges.
Sample Input
4 1 2 2 3 3 4
Sample Output
1
Hint
Only edge $(2, 3)$ can be removed.
题意: 给你n个节点的树 你的任务是删除边使得 偶数块尽量的多。
思路: 比较简单的一个树上的搜索。。 思路就是从一个节点开始搜索,然后如果碰见某一个节点的 孩子个数为 偶数 就删除这个
节点和他父亲之间的边(其实实现的时候 不用真的删除 )并且最终结果加一。
代码:
#include<stdio.h> #include<string.h> #include<vector> #include<iostream> #include<algorithm> #define N 100005 using namespace std; vector< int >edge[N]; int n; int cnt; int dfs(int u,int fa) { int sum=0; for(int i=0;i<edge[u].size();i++) { int v=edge[u][i]; if(v==fa) continue; int num=dfs(v,u); //printf("v: %d %d\n",v,num); if(num%2==1) sum+=num; else cnt++; } //printf("%d %d\n",u,sum); return sum+1; } int main() { int u,v; scanf("%d",&n); for(int i=1;i<n;i++) { scanf("%d %d",&u,&v); edge[u].push_back(v); edge[v].push_back(u); } cnt=0; dfs(1,-1); printf("%d\n",cnt); return 0; }