codeforces 982C (dfs)
程序员文章站
2024-01-19 21:13:46
题意描述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
上一篇: 329. 矩阵中的最长递增路径 深度优先+记忆化递归
下一篇: BlueHost香港主机使用心得
推荐阅读
-
Codeforces Round #248 (Div. 2) A题_html/css_WEB-ITnose
-
codeforces 260 div2 A,B,C_html/css_WEB-ITnose
-
Codeforces Round #262 (Div. 2) A,B,C_html/css_WEB-ITnose
-
二叉树非递归dfs——简单思路搞定前中后序遍历
-
codeforces Round #275(div2) D解题报告
-
codeforces 982C (dfs)
-
Codeforces Round #254 (Div. 2) A. DZY Loves Chessboard
-
Codeforces Round #227 (Div. 2)A. George and Sleep
-
Codeforces Round #256 (Div. 2) 题解_html/css_WEB-ITnose
-
Codeforces Round #247 (Div. 2) ABC_html/css_WEB-ITnose