两数之和变形,CF 1278C - Berry Jam

目录

一、题目

1、题目描述

2、输入输出

2.1输入

2.2输出

3、原题链接

二、解题报告

1、思路分析

2、复杂度

3、代码详解


一、题目

1、题目描述

2、输入输出

2.1输入
2.2输出

3、原题链接

1278C - Berry Jam


二、解题报告

1、思路分析

考虑保留的前后缀满足什么特点?

前缀中 1的数目 - 2的数目 = 后缀中 2的数目 - 1的数目

那么我们发现这就是一个两数之和问题

我们哈希表预处理最靠右 前缀中 1的数目 - 2的数目 的位置

然后倒着遍历后缀,计数维护最长前后缀长度即可

2、复杂度

时间复杂度: O(NlogN)(可以将下标映射从而避免map的访问开销)空间复杂度:O(N)

3、代码详解

复制代码
 ​
cpp 复制代码
#include <bits/stdc++.h>

using i64 = long long;
using i32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;

constexpr int inf32 = 1E9 + 7;
constexpr i64 inf64 = 1E18 + 7;
constexpr int P = 998'244'353;

void solve() {
	int n;
	std::cin >> n;
	
	int m = n * 2;

	std::vector<int> a(m);
	std::map<int, int> pre, suf;

	for (int i = 0; i < m; ++ i) std::cin >> a[i];

	for (int i = 0, f = 0; i < n; ++ i) {
		f += (a[i] & 1 ? 1 : -1);
		pre[f] = i;
	}

	int res = m;

	for (int i = m - 1, f = 0; i >= n; -- i) {
		f += (a[i] & 1 ? -1 : 1);
		if (pre.contains(f)) {
			res = std::min(res, i - pre[f] - 1);
		}
		if (f == 0)
			res = std::min(res, i);
	}

	if (pre.contains(0))
		res = std::min(res, m - pre[0] - 1);

	std::cout << res << '\n';
}

auto FIO = []{
	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	std::cout.tie(nullptr);
	return 0;
}();

int main () {
	#ifdef DEBUG
		freopen("in.txt", "r", stdin);
		freopen("out.txt", "w", stdout);
	#endif
	
	int T = 1;
	std::cin >> T;
	while (T --) {
		solve();
	}

	return 0;
}
相关推荐
fab 在逃TDPIE5 分钟前
Sentaurus TCAD 仿真教程(十)
算法
天赐学c语言24 分钟前
12.19 - 买卖股票的最佳时机 && const的作用
c++·算法·leecode
菜鸟233号28 分钟前
力扣78 子集 java实现
java·数据结构·算法·leetcode
yesyesyoucan31 分钟前
在线魔方解谜站:从零入门到精通的智能魔方学习平台
学习·算法
Han.miracle32 分钟前
数据结构与算法--008四数之和 与经典子数组 / 子串问题解析
数据结构·算法
!停33 分钟前
字符函数和字符串函数
算法
AI科技星1 小时前
圆柱螺旋运动方程的一步步求导与实验数据验证
开发语言·数据结构·经验分享·线性代数·算法·数学建模
FONE_Platform1 小时前
FONE食品饮料行业全面预算解决方案:构建韧性增长
人工智能·算法·全面预算·全面预算管理系统·企业全面预算
月明长歌1 小时前
【码道初阶】【Leetcode94&144&145】二叉树的前中后序遍历(非递归版):显式调用栈的优雅实现
java·数据结构·windows·算法·leetcode·二叉树
DanyHope2 小时前
《LeetCode 49. 字母异位词分组:哈希表 + 排序 全解析》
算法·leetcode·哈希算法·散列表