题解:P14427 [JOISC 2014] 电压 / Voltage
题意简述
现在有一个无向图(不一定连通),要你选择一条边,这条边必须满足:
- 删除该边后,原图(的各个连通块)能构成二分图。
问你一共有几条这样的边可以选择。
思路
基本观察与思路
回顾二分图成立的条件:图中没有奇环。而如果一条边在奇环上,那么删去它必定会破坏该奇环。因此,我们能够选择的边一定在所有的奇环上。同理,我们可以退出,这些边一定不在任意一个偶环上。
因此,我们要统计的边(假定为
考虑统计这些边的数量。
但原图中可能有各种各样的环,比如共顶点的、边重合的,怎么找到这些环,又如何判断边是否在某些环上呢?
这里,我们先将原图的 DFS 树构建出来。无向图的 DFS 树一定不存在横叉边,只存在返祖边。这些名词不了解的可以自行搜索学习。
那么,一条返祖边(也就是非 DFS 树边,简称非树边)一定能和其两个端点的树上路径的边构成一个环。如下图:
这样的环的边数的奇偶性是非常好统计的:设深度较小的点的深度为
但是这里只展示了只包含一条非树边的环,那要是一个环不止包含一条非树边呢?
这里有一个非常重要的结论:
- 我们只需要统计包含一条非树边的环的奇偶性以及个数,不需要考虑包含多条非树边的环。
这个结论的证明放在了题解的末尾,感兴趣的可以去看一看。
既然这样,我们每条树边在多少个奇环和偶环中是可以统计的了:直接树上差分即可。在树上差分完成并前缀和统计之后,我们记
遍历 DFS 树以统计有多少条树边满足上面的条件即可。
注意一个边界情况:当
细节问题
注意原图可能不连通,但是我们只能在整个图中删除一条边。因此我们最后统计的
注意原图可能存在重边,但重边应该被算作一个偶环。因此在 DFS 的时候,我们不能只记录当前点的父节点是哪个点,而应该要记录我们是从父节点的哪条边过来的。因此要给边编号,并在 DFS 中记录。
上面的细节问题属于思路中的边界情况和代码设计的问题。剩下的可能的细节问题就是代码实现的问题了,这里就不过多赘述了。
代码
有详细注释,可以细品。
:::success[C++ 代码]
#include <iostream>
#include <vector>
// 边。
struct Edge {
int to;
int id; // 边的编号。
};
static int nodes_cnt, edges_cnt;
static std::vector<std::vector<Edge>> adj; // 邻接表
static std::vector<int> depth;
static std::vector<int> odd; // 记录 DFS 树上某个点与父节点的连边在多少个奇环上。
static std::vector<int> even; // 同上,但记录偶环。
static std::vector<bool> vis;
static std::vector<bool> is_tree; // 是否是树边,第二次遍历有用。
static int odd_cnt; // 全局奇环总数。
static void solve();
static void dfs(int node, int parent_id);
static void dfs_calc(int node, int parent_id, int& result);
int main() {
std::cin.tie(nullptr)->sync_with_stdio(false);
solve();
return 0;
}
static void solve() {
std::cin >> nodes_cnt >> edges_cnt;
adj.resize(nodes_cnt + 1);
for (int i = 1; i <= edges_cnt; i++) {
int u, v;
std::cin >> u >> v;
adj[u].push_back(Edge {
.to = v,
.id = i,
});
adj[v].push_back(Edge {
.to = u,
.id = i,
});
}
depth.resize(nodes_cnt + 1);
vis.assign(nodes_cnt + 1, false);
is_tree.assign(edges_cnt + 1, false);
odd.assign(nodes_cnt + 1, 0);
even.assign(nodes_cnt + 1, 0);
// 第一次遍历:遍历所有连通块,记录奇环总数并统计边在多少个奇环和偶环上。
for (int i = 1; i <= nodes_cnt; i++) {
if (!vis[i]) {
depth[i] = 1;
dfs(i, 0);
}
}
// 第二次遍历:遍历所有连通块,对树上差分做前缀和,并统计可被选择的边的数量。
int answer = 0;
for (int i = 1; i <= nodes_cnt; i++) {
if (depth[i] == 1) {
dfs_calc(i, 0, answer);
}
}
// 奇环总数为 1,则该奇环的非树边也可被选择。
if (odd_cnt == 1) {
answer++;
}
std::cout << answer << '\n';
}
// 注意,parent_id 记录从父节点到当前节点的边的编号。
static void dfs(int node, int parent_id) {
vis[node] = true;
for (const Edge& edge : adj[node]) {
if (edge.id == parent_id) {
continue;
}
if (!vis[edge.to]) { // 新树边。
depth[edge.to] = depth[node] + 1;
is_tree[edge.id] = true;
dfs(edge.to, edge.id);
} else if (depth[edge.to] < depth[node]) { // 返祖边。
int length = depth[node] - depth[edge.to] + 1;
// 记录树上差分。
if (length % 2 == 0) { // 偶环。
even[node]++;
even[edge.to]--;
} else { // 奇环。
odd[node]++;
odd[edge.to]--;
odd_cnt++;
}
}
}
}
// parent_id 同上。result 记录答案。
static void dfs_calc(int node, int parent_id, int& result) {
for (const Edge& edge : adj[node]) {
if (edge.id == parent_id) {
continue;
}
if (!is_tree[edge.id]) {
continue;
}
dfs_calc(edge.to, edge.id, result);
// 对差分做前缀和。
odd[node] += odd[edge.to];
even[node] += even[edge.to];
}
// 判断是否是可被选择的边。
// 注意根节点没有与父节点连接的边。
if (parent_id != 0 && odd[node] == odd_cnt && even[node] == 0) {
result++;
}
}
:::
证明:只需考虑含一条非树边的环
证明:在 DFS 树上统计奇环和偶环数量的时候,我们只需要考虑只包含一条非树边的环,而不需要考虑包含更多非树边的环。
设
我们把环表示为边的集合,是为了后面好进行推导和证明。
对于两个集合
其中
换句话说,如果某个元素在对称差运算的集合集合中出现了奇数次,则该元素会在最后的结果集合中出现;反之(出现偶数次),则不会在最后的结果集合中出现。
结论:原图中任意一个环
其中
证明该结论非常容易。以下是简要证明。
设环
另外我们可以证明每个环
假设原图中所有环构成的集合为
因此后文我们用
设
接下来我们终于可以形式化地表示我们要证明的结论了!
假设有一条树边
很明显,树边
意思就是说,我们要证明的,是
这样就能证明我们的算法的正确性。
根据上面的论述,我们有:
所以有:
上面这个式子中的
我们记
根据对称差的性质,树边
我们将
根据环
因此我们有:
因此我们可以证明关于边
证毕。
证明:在所有奇环上的边不可能在偶环上
我们还可以证明这样一个结论:在所有奇环上的边,不可能在偶环上。
这个可以使用反证法证明。如图:
我们假设红边在所有的奇环上,其中一个奇环是红边与蓝边组成的;红边还在一个偶环上,即红边和绿边组成的环。那么绿边与蓝边也能构成一个奇环,但红边不在这个奇环上,矛盾。因此,如果一条边在所有奇环上,那么它不可能在任意一个偶环上。证毕。
花絮
我当时写代码的时候没有注意“细节问题”中的第一条:我虽然考虑了不同连通块的处理,但是我每个连通块统计答案的时候判断的是“局部奇环总数”,也就是该连通块中的奇环数量,而不是“全局奇环总数”,也就是整个图中的奇环数量。这个问题只会导致两个测试点 WA,因此我以为是我的代码问题,一直在检查代码逻辑,甚至还以为是内存问题或未定义行为,还拿 Rust 写了一遍检查一下……结果最后发现是奇环数量计错了,多了很多不合法的答案。
附最后正确的 Rust 代码:
:::success[Rust 代码]
use std::io;
#[derive(Clone, Default)]
struct Edge {
to: usize,
id: usize,
}
struct Context {
adj: Vec<Vec<Edge>>,
depth: Vec<i32>,
odd: Vec<i32>,
even: Vec<i32>,
vis: Vec<bool>,
is_tree: Vec<bool>,
odd_cnt: i32,
}
fn main() {
solve();
}
fn solve() {
let input = io::stdin();
let mut line = String::new();
input.read_line(&mut line).unwrap();
let mut iter = line.split_whitespace();
let nodes_cnt = iter.next().unwrap().parse::<usize>().unwrap();
let edges_cnt = iter.next().unwrap().parse::<usize>().unwrap();
let mut ctx = Context {
adj: vec![vec![]; nodes_cnt + 1],
depth: vec![0; nodes_cnt + 1],
odd: vec![0; nodes_cnt + 1],
even: vec![0; nodes_cnt + 1],
vis: vec![false; nodes_cnt + 1],
is_tree: vec![false; edges_cnt + 1],
odd_cnt: 0,
};
for i in 1..=edges_cnt {
let mut line = String::new();
input.read_line(&mut line).unwrap();
let mut iter = line.split_whitespace();
let u = iter.next().unwrap().parse::<usize>().unwrap();
let v = iter.next().unwrap().parse::<usize>().unwrap();
ctx.adj[u].push(Edge {
to: v,
id: i,
});
ctx.adj[v].push(Edge {
to: u,
id: i,
});
}
for i in 1..=nodes_cnt {
if !ctx.vis[i] {
ctx.depth[i] = 1;
dfs(&mut ctx, i, 0);
}
}
let mut answer = 0;
for i in 1..=nodes_cnt {
if ctx.depth[i] == 1 {
dfs_calc(&mut ctx, i, 0, &mut answer);
}
}
if ctx.odd_cnt == 1 {
answer += 1;
}
println!("{}", answer);
}
fn dfs(ctx: &mut Context, node: usize, parent_id: usize) {
ctx.vis[node] = true;
let adj = ctx.adj[node].clone();
for edge in adj {
let edge = edge.clone();
if edge.id == parent_id {
continue;
}
if !ctx.vis[edge.to] {
ctx.depth[edge.to] = ctx.depth[node] + 1;
ctx.is_tree[edge.id] = true;
dfs(ctx, edge.to, edge.id);
} else if ctx.depth[edge.to] < ctx.depth[node] {
let length = ctx.depth[node] - ctx.depth[edge.to] + 1;
if length % 2 == 0 {
ctx.even[node] += 1;
ctx.even[edge.to] -= 1;
} else {
ctx.odd[node] += 1;
ctx.odd[edge.to] -= 1;
ctx.odd_cnt += 1;
}
}
}
}
fn dfs_calc(ctx: &mut Context, node: usize, parent_id: usize, result: &mut i32) {
let adj = ctx.adj[node].clone();
for edge in adj {
if edge.id == parent_id {
continue;
}
if !ctx.is_tree[edge.id] {
continue;
}
dfs_calc(ctx, edge.to, edge.id, result);
ctx.odd[node] += ctx.odd[edge.to];
ctx.even[node] += ctx.even[edge.to];
}
if parent_id != 0 && ctx.odd[node] == ctx.odd_cnt && ctx.even[node] == 0 {
*result += 1;
}
}
:::