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.
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 a single integer kk — the maximum number of edges that can be removed to leave all connected components with even size, or −1−1if it is impossible to remove edges in order to satisfy this property.
4 2 4 4 1 3 1
1
3 1 2 1 3
-1
10 7 1 8 4 8 10 4 7 6 5 9 3 3 5 2 10 2 5
4
2 1 2
0
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
题意:给了n个顶点和n-1条边,保证给出的是一棵树,如果删除一条边能够使得剩下的连通部分均有偶数个点,则记录这条边,求最多能删除的边的个数
分析:如果给出的点的个数是奇数,无论怎么删除边都不会产生全是偶数的连通子树,输出-1。如果给出的点的个数是偶数,对于每一个结点u,父结点为v,u及其子树的结点总数为偶数的话就可以删除e(u,v),因为偶数-偶数还是偶数,统计所有这样的结点个数即可。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
vector<int>G[maxn];
int ans[maxn],vis[maxn];
int dfs(int x)
{
for(int i = 0; i < G[x].size(); i++)
{
int u = G[x][i];
if(!vis[u])
{
vis[u] = 1;
ans[x] += dfs(u);
vis[u] = 0;
}
}
ans[x]++;
return ans[x];
}
int main()
{
int n;
cin>>n;
for(int i = 1; i <= n - 1; i++)
{
int u,v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
vis[1] = 1;
dfs(1);
// for(int i = 1; i <= n; i++)
// printf("%d ",ans[i]);
// printf("\n");
if(n % 2)
printf("-1\n");
else
{
int cnt = 0;
for(int i = 1; i <= n; i++)
{
if(ans[i] % 2 == 0)
cnt++;
}
cout<<cnt - 1<<endl;
}
return 0;
}
本文介绍了一道关于树形结构的算法题Cut'emall!,任务是在保证所有剩余连通部分节点数为偶数的前提下,求解可以删除的最大边数。文章分析了题目条件,并给出了实现代码。
414

被折叠的 条评论
为什么被折叠?



