跳到正文

题解

题解:CF1039C Network Safety

#SUSPENDED#约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年3月8日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 5 分钟
获赞
4
题目
CF1039C

版本

  1. v1当前

更好的阅读体验(隐藏评论区)?

题目摘要

给一张带点权的图(网络结构),和一个整数 k(k∈[0,60])k(k\isin[0,60])。
如果这张图是”安全”的,当且仅当每条边连接的两个点点权互不相同。 对于 ∀x(x∈[0,2k−1])\forall x(x\isin[0,2^k-1]),选出一个由点构成的集合 ss,使得将 ss 中的所有点的点权全部 ⊕x\oplus x 后,图仍然”安全”。找出这样的 x&sx\& s 对的数量。
上文中,⊕\oplus 代表二进制异或运算,而 &\& 并不代表二进制与运算,而是单纯的凑对关系。

前置知识

  • 二进制异或运算的一些性质(这个后面会说到,这里就不贴链接了)
  • 并查集
  • 快速幂

正题开始

既然提到了”异或”和边,我们可以先看看它们之间拥有什么样的关系。
设边连结了点 uu 和 vv,点权为 cuc_u 和 cvc_v:
如果 a=cu⊕cva=c_u\oplus c_v,则

  • a⊕cu=cva\oplus c_u=c_v
  • a⊕cv=cua\oplus c_v=c_u

当题中 xx 取 aa 时,如果 uu 选 vv 不选,或者 vv 选 uu 不选,都会导致修改后的 u,vu,v 点权相同。
而剩下的情况,并不会导致最终两点点权相同(可自行证明)。
于是我们在 xx 取 cu⊕cvc_u\oplus c_v 时合并两点即可。
“合并操作”的实现方法可以使用并查集来维护。

实现方法

考虑如何统计答案。
我们设 SS 为执行到这一步时,连通块的大小。
在没有出现上述情况的条件下,每个点每个 xx 都可以选或不选,答案为 2n+k2^{n+k}。
每次合并节点后,将答案减去 2n−S2^{n-S} 后,合并联通块。
然后将答案加上 2n−S2^{n-S}。
算幂用快速幂即可。

时间复杂度

  • 输入点权:Θ(n)\Theta(n)。
  • 遍历边:Θ(m)\Theta(m)。
  • 快速幂:Θ(log2n)\Theta(\text{log}_2n)。
  • 并查集:Θ(α(n))\Theta(\alpha(n)),其中 α()\alpha() 为反阿克曼函数。
  • 总时间复杂度:Θ(n+m(log2n+α(n)))\Theta (n+m(\text{log}_2 n+\alpha(n)))。

空间复杂度

  • 点权:Θ(n)\Theta(n)。
  • 并查集:虽然每个点都有很多种合并需要的权值,但是边数不超过 mm 条,所有可能的合并权值也只有 mm 种,总空间复杂度为 Θ(m)\Theta(m) 。为了达到上述效果,我们可以使用查询及赋值只需要 Θ(1)\Theta(1) 时间复杂度的无序映射。
  • 总空间复杂度:Θ(n+m)\Theta(n+m)。

代码

码风不良,dalao 们不喜勿喷。

C++
#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;
}
原文
存档评论3 条抓取于