题解:CF1039C Network Safety
zhangzhixing99 · · 题解
更好的阅读体验(隐藏评论区)?
题目摘要
给一张带点权的图(网络结构),和一个整数
如果这张图是"安全"的,当且仅当每条边连接的两个点点权互不相同。
对于
上文中,
前置知识
- 二进制异或运算的一些性质(这个后面会说到,这里就不贴链接了)
- 并查集
- 快速幂
正题开始
既然提到了"异或"和边,我们可以先看看它们之间拥有什么样的关系。
设边连结了点u 和v ,点权为c_u 和c_v :
如果a=c_u\oplus c_v ,则 -
a\oplus c_u=c_v -
a\oplus c_v=c_u
当题中
而剩下的情况,并不会导致最终两点点权相同(可自行证明)。
于是我们在
"合并操作"的实现方法可以使用并查集来维护。
实现方法
考虑如何统计答案。
我们设
在没有出现上述情况的条件下,每个点每个
每次合并节点后,将答案减去
然后将答案加上
算幂用快速幂即可。
时间复杂度
- 输入点权:
\Theta(n) 。 - 遍历边:
\Theta(m) 。 - 快速幂:
\Theta(\text{log}_2n) 。 - 并查集:
\Theta(\alpha(n)) ,其中\alpha() 为反阿克曼函数。 - 总时间复杂度:
\Theta (n+m(\text{log}_2 n+\alpha(n))) 。空间复杂度
- 点权:
\Theta(n) 。 - 并查集:虽然每个点都有很多种合并需要的权值,但是边数不超过
m 条,所有可能的合并权值也只有m 种,总空间复杂度为\Theta(m) 。为了达到上述效果,我们可以使用查询及赋值只需要\Theta(1) 时间复杂度的无序映射。 - 总空间复杂度:
\Theta(n+m) 。代码
码风不良,dalao 们不喜勿喷。
#include <bits/stdc++.h> using namespace std;
define EOL '\n'
const int mod = 1e9 + 7;
int n, m, k; long long w[500010]; unordered_map<long long, int> cnt, top[500010]; long long ans;
int Find(int u, long long key) { if (u == top[u][key]) { return u; } return top[u][key] = Find(top[u][key], key); }
long long qpow(long long bas, long long t) { long long ret = 1, mul = bas; while (t) { if (t & 1) { ret = mul; ret %= mod; } mul = mul; mul %= mod; t >>= 1; } return ret; }
int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n >> m >> k; for (int i = 1; i <= n; ++i) { cin >> w[i]; } ans = qpow(2, n + k); for (int i = 1; i <= m; ++i) { int u, v; cin >> u >> v; long long x = w[u] ^ w[v]; if (!top[u].count(x)) { top[u][x] = u; } if (!top[v].count(x)) { top[v][x] = v; } if (Find(u, x) == Find(v, x)) { continue; } top[Find(v, x)][x] = Find(u, x); ans = ((ans - qpow(2, n - cnt[x])) % mod + mod) % mod; ++cnt[x]; ans = (ans + qpow(2, n - cnt[x])) % mod; } cout << ans << EOL; return 0; }