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
上一篇: 历史上真实的弘瞻是什么身份?他为什么会过继给果亲王允
下一篇: 市场500亿 智能硬件创业路在何方?
推荐阅读
-
岛屿数量(经典 DFS 和 BFS 高频题 商汤、字节面试题)
-
Codeforces Round #595 (Div. 3)D1D2 贪心 STL
-
『ACM C++』 Codeforces | 1066B - Heaters
-
迷宫救人——DFS小题
-
数据结构算法(统计封闭岛屿的数目dfs)
-
『ACM C++』 Codeforces | 1003C - Intense Heat
-
Codeforces 939A题,B题(水题)
-
CodeForces 29D Ant on the Tree
-
Codeforces Global Round 9-C. Element Extermination
-
codeforces 712B Memory and Trident