两数之和变形,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;
}
相关推荐
小李子呢02111 天前
前端八股6---v-model双向绑定
前端·javascript·算法
2301_822703201 天前
Flutter 框架跨平台鸿蒙开发 - 创意声音合成器应用
算法·flutter·华为·harmonyos·鸿蒙
cmpxr_1 天前
【C】数组名、函数名的特殊
c语言·算法
KAU的云实验台1 天前
【算法精解】AIR期刊算法IAGWO:引入速度概念与逆多元二次权重,可应对高维/工程问题(附Matlab源码)
开发语言·算法·matlab
会编程的土豆1 天前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
大熊背1 天前
如何利用Lv值实现三级降帧
算法·自动曝光·lv·isppipeline
大尚来也1 天前
驾驭并发:.NET多线程编程的挑战与破局之道
java·前端·算法
向阳而生,一路生花1 天前
深入浅出 JDK7 HashMap 源码分析
算法·哈希算法
君义_noip1 天前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
摸个小yu1 天前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表