跳到正文

题解

题解:P13674 [GCPC 2023] Investigating Frog Behaviour on Lily Pad Patterns

Ayanami_404约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年10月27日
篇幅
约 3 分钟
题目
P13674

版本

  1. v2当前
  2. v1

题目简述

有 nn 只青蛙,初始时分别位于位置 x1,x2,…,xnx_1, x_2, \dots, x_n 上,其中 x1<x2<⋯<xnx_1 < x_2 < \dots < x_n(位置编号为正整数,单调递增)。物体仅能向编号更大的方向移动,每次移动时,会落到当前位置右侧最近的空位置(即无其他物体的位置)。

给定 qq 次移动记录,按时间顺序排列,每次记录指定一只青蛙(第 ii 个)进行一次移动。需输出每次移动后该物体所在的位置编号。

思路

使用 set 以高效地实现插入、删除。
由于题目中明确了跳跃方向为从左往右的,说明数据具有单调性,考虑使用二分查找。
在输入时首先对于 set 进行预处理,将所有没有青蛙站着的荷叶放入 set。随后在每次对第 ii 只青蛙的查询时调用 upper_bound 查找第一个 >xi\gt x_i 的荷叶,输出 upper_bound 结果,将 upper_bound 结果从 set 中删去并将 xix_i 加入。

此处的 vis 数组使用 bitset 实现,空间复杂度为 O(nw)O(\frac{n}{w})(w=32w=32),也可以使用正常的 C 风格布尔数组代替。

时间复杂度

set(大部分 C++ 运行库底层使用红黑树实现)的单次插入操作时间复杂度为 O(log⁡n)O(\log n),upper_bound(二分查找)的单次查找时间复杂度为 O(log⁡n)O(\log n),外层循环 qq 次,总体程序时间复杂度为 O(qlog⁡n)O(q\log n)。

参考程序

C++
#include <bitset>
#include <cstdio>
#include <set>
#define fex(a, b) freopen(a, "r", stdin);freopen(b, "w", stdout)
using namespace std;

long long read() {
	char c;
	long long r=0, f=1;
	while(!((c=getchar())>='0' && c <= '9')) {
		if(c=='-')f=-f;
	}
	while(c >= '0' && c <= '9') {
		r=r*10+c-'0';
		c=getchar();
	}
	return r*f;
}

const long long maxn = 2e6;
bitset<2000005> vis;
//bool vis[200005];
long long n, q, I;
long long x[200005];
set<long long> s;

int main() {
//	fex("~.in", "~.out");
	n=read();
	for(int i = 1; i <= n; i++)x[i]=read(), vis[x[i]]=1;
	for(int i = 1; i <= maxn; i++)if(!vis[i])s.insert(i);
	q=read();
	while(q--) {
		I=read();
		set<long long>::iterator si = s.upper_bound(x[I]);
		printf("%lld\n", (*si));
		s.insert(x[I]);
		x[I]=(*si);
		s.erase(*si);
	}

	return 0;
}

抄袭、复制题解,以达到刷 AC 率 / AC 数量或其他目的的行为,在洛谷是严格禁止的。

提交记录

戳我戳我

原文