F - Oddly Similar
F - Oddly Similar
Problem Statement
There are sequences of length , denoted as . The -th sequence is represented by integers .
Two sequences and of length are said to be similar if and only if the number of indices such that is odd.
Find the number of pairs of integers satisfying such that and are similar.
Constraints
- All input values are integers.
Input
The input is given from Standard Input in the following format:
Output
Print the answer as an integer.
Sample Input 1
3 3
1 2 3
1 3 4
2 3 4
Sample Output 1
1
The pair satisfies the condition because there is only one index such that , which is .
The pairs do not satisfy the condition, making the only pair that does.
Sample Input 2
6 5
8 27 27 10 24
27 8 2 4 5
15 27 26 17 24
27 27 27 27 27
27 7 22 11 27
19 27 27 27 27
Sample Output 2
5
解题思路
纯暴力题,开优化甚至能在时限内跑 的暴力。正解是用 std::bitset
优化到 。
最暴力的做法是枚举当前行 和之前行 ,然后比较两行的元素。对于某一列 ,可以发现只有 的行 才会与第 行有相同的元素的贡献。所以对于第 行,当枚举到第 列时,我们希望能快速知道前面有哪些行 的 。
只需开一个 std::bitset<n>
数组 ,表示前 行中,第 列有哪些行的值为 ,这些行用状态压缩来表示。因此在枚举到第 行时,用一个 std::bitset<n>
变量 来维护第 行与之前每一行相同元素数量的奇偶性, 中的第 位表示第 行与第 行中相同元素数量的奇偶性。枚举每一列 ,并令 。最后 中 的数量就是第 行与之前相同元素数量为奇数的行的数量。
AC 代码如下,时间复杂度为 :
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2005, M = 1005;
int a[N][N];
bitset<N> st[N][M];
int main() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &a[i][j]);
}
}
int ret = 0;
for (int i = 0; i < n; i++) {
bitset<N> t;
for (int j = 0; j < m; j++) {
t ^= st[j][a[i][j]];
}
ret += t.count();
for (int j = 0; j < m; j++) {
st[j][a[i][j]][i] = 1;
}
}
printf("%d", ret);
return 0;
}
参考资料
AtCoder Beginner Contest 348:https://www.cnblogs.com/Lanly/p/18118195
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/18121306
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2021-04-08 用优先队列构造Huffman Tree及判断是否为最优编码的应用
2021-04-08 Huffman Codes