当前位置:网站首页>树与二分图【思维】
树与二分图【思维】
2022-07-17 20:46:00 【Codiplay】
题意
给定一颗树,可以在没有直接连边的两个节点上加一条边,满足加边后的图是二分图
思路
一张图是二分图的条件等价于没有奇数环,所以此题要你统计出所有节点个数为偶数的子树
从一个点出发,记录节点个数,注意到如果对于当前这个点来说是奇数个的话,去除掉此点数目一定为偶数,则这个“信息”可以继续被利用。
用异或给每个节点定性,1为奇数0为偶数
从节点1走到节点0所包含的节点一定是偶数个,则是一组为节点个数为偶数的子树,所以:统计一颗树的节点个数为偶数的子树,只需用节点标记为1的数目乘上节点标记为0的数目,得到的便是节点个数为偶数的子树。
题目中说要符合没有直接连边,又因为相邻的节点必一个为0一个为1,数目为2,符合为偶数个的条件,但是有直接连边,所以要去掉边的个数(n - 1)即为答案
代码
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 100000;
int n, cnt0, cnt1;
vector<int> G[N];
void dfs(int u, int fa, int s)
//这样写不需要再开个vis防止倒退。
//因为是棵树,只需要保证当前节点不会回到fa即可
{
if(s == 1)cnt1 ++;
else cnt0 ++;
for (int i = 0; i < (int)G[u].size(); i ++ )
{
if(G[u][i] == fa)continue;
dfs(G[u][i], u, s ^ 1);
}
}
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
cin >> n;
for (int i = 1, u, v; i < n; i ++ ) {
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1, 1, 1);
cout << (cnt1 * cnt0) - n + 1 << '\n';
return 0;
}
边栏推荐
- 【C语言】扫雷介绍与实现【数组与函数】
- Logu: p4516 [jsoi2018] stealth action (tree DP, tree grouping knapsack statistical scheme number)
- Redis源码与设计剖析 -- 4.跳跃表
- No.3 advanced assembly
- NFT市场格局仍未变化,Okaleido能否掀起新一轮波澜?
- [dynamic programming] - longest ascending subsequence model
- topy库的安装(拓扑优化软件)
- Unveil the mystery of service grid istio service mesh
- No.2 compilation preliminary
- Interview with Android development companies, make these three preparations and plan yourself
猜你喜欢

Comprehensive analysis of C language multimedia open source framework GStreamer

4某公司在6个城市c1,c2,c3…c6中有分公司,已知城市ci到cj(I,j=1,2,3,…6)的联通情况下及费用的大小列于以下带权邻接矩阵中C中

96. 不同的二叉搜索树

华为无线设备配置动态负载均衡

Robotics at google:laura Graesser | i-sim2real: strengthen the learning robot strategy in the close human-computer interaction cycle

Chrome plug-ins for information collection

类3实践

数据库的增删改查

非凸优化问题经典必看综述“从对称性到几何性”,罗切斯特大学等

ModuleNotFoundError: No module named ‘_ distutils_ hack‘
随机推荐
关于数据字典的一些解惑
Some puzzles about data dictionary
FreeRTOS个人笔记-支持多优先级
Homework on the first day of summer rhcsa training
ImportError: DLL load failed while importing win32api: 找不到指定的程序。
类3实践
2. Sum of three numbers
AcWing 134. Double ended queue
通达信开户是真的吗?通达信开户安全吗?
分析并HOOK SSHD来劫持密码
Introduction:Multiple DataFrames
Redis源码与设计剖析 -- 3.字典
函数初认识-下
Huawei Technologies:Jonatan Krolikowski | 从设计到部署零接触深度强化学习WLANs
Several small open source projects of mine over the years
CBS type PVC recycling strategy
[7.14] code source - [open box] [XOR inverse] [continuous subsequence] [trigonometric fruit count]
Tke mounts CFS across cloud networking
Run through caffe resnet-50 network to realize image classification -- Based on Huawei cloud ai1s
No.6 representation and operation of floating point numbers