Cut 'em all!

本文探讨了在树形结构中使用深度优先搜索(DFS)算法解决特定问题的方法。问题的核心在于确定一棵树中最多可以删除多少条边,使得每个剩余的连通组件的顶点数量均为偶数。文章首先介绍了问题背景,随后详细阐述了解决方案的思路,并提供了完整的AC代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值