欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

codeforces 982C (dfs)

程序员文章站 2022-05-10 10:04:49
题意描述You’re given a tree with 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.给定一棵树,询问最多删除多少条边可以使每个连通块的数量都是偶数思路这道题的even最初理解成了相同的...

题意描述

You’re given a tree with 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.

给定一棵树,询问最多删除多少条边可以使每个连通块的数量都是偶数

思路

这道题的even最初理解成了相同的意思,导致没读懂题。要想最多删除边,肯定要使每个连通块的数量都为2。如果结点数是奇数,则不满足题意,输出-1.否则就dfs寻找所有结点的子结点数,如果子结点数量为偶数,则说明可以删除一条边。

AC代码

#include<bits/stdc++.h>
#define x first
#define y second
#define PB push_back
#define mst(x,a) memset(x,a,sizeof(x))
#define all(a) begin(a),end(a)
#define rep(x,l,u) for(ll x=l;x<u;x++)
#define rrep(x,l,u) for(ll x=l;x>=u;x--)
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long ll;
const int N=2*1e5+10;
const int M=1e6+10;
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;
vector<int> g[N];
int n;
int ans=0;
bool used[N];
int dfs(int u){
    int res=0;
    used[u]=true;
    rep(i,0,g[u].size()){
        int v=g[u][i];
        if(!used[v]){
            int cur=dfs(v);
            if(cur%2==0) ans++;
            res+=cur;
        }
    }
    return res+1;
}
void solve(){
    cin>>n;
    rep(i,0,n-1){
        int x,y;cin>>x>>y;
        g[x].PB(y);
        g[y].PB(x);
    }
    if(n%2!=0){
        cout<<-1<<endl;
        return;
    }
    dfs(1);
    cout<<ans<<endl;
}
int main(){
    IOS;
    solve();
    return 0;
}

本文地址:https://blog.csdn.net/weixin_45729946/article/details/107610660