跳到正文

题解

题解:P10844 [EGOI2024] Infinite Race / 无限赛跑

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

文章信息

发布
2024年8月21日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 3 分钟
题目
P10844

版本

  1. v2当前
  2. v1

P10844 Infinite Race

原题链接

题意详解

Anika 是一位好胜心很强的参赛者,所以 Ta 只记录了:

  1. Ta 超过的参赛者编号;
  2. 被 Ta 超过的参赛者编号。

现在你需要求出 Ta 至少跑了多少圈(参赛者速度不恒定)。

思路

以贪心的思想我们不难想到,要保证 Anika 一定跑过了一圈,那 Ta 一定满足超过同一个参赛者两次,然后轻松打出代码,得到 29pts 。

代码如下:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
int vis[N];
int n,q,x;
int main(){
	memset(vis,0,sizeof vis);
	scanf("%d%d",&n,&q);
	int ans=0;
	while(q--){
		scanf("%d",&x);
		if(x>0){
			if(vis[x]>=1) ans++;
			else ++vis[x];
		}else vis[-x]=0;
	}
	cout<<ans<<endl;
	return 0;
}

分析样例 3 我们发现:如果一定跑过一圈,那么超过同一个参赛者两次。这是一个真命题。然而它的逆命题却是一个假命题。

要想跳过这个小坑,我们只需要在每次更新 ans 的值时将 vis(i)vis(i) 清空即可。我在其他题解中有看到用 memset 或是 fill 进行维护的,这样维护每次需要更新 2×1052 \times 10^5 次,这个运算规模是我们所不能接受的。

其实我们可以将每次经过修改的参赛者编号存入一个队列或者栈中,在进行清空 vis(i)vis(i) 操作时就只需要将数组中已标记过的元素清零即可。

Ac code

C++
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
int vis[N];
int n,q,x;
stack<int> s;
int main(){
	memset(vis,0,sizeof vis);
	scanf("%d%d",&n,&q);
	int ans=0;
	while(q--){
		scanf("%d",&x);
		if(x>0){
			if(vis[x]){
				ans++;
				while(!s.empty()){
					vis[s.top()]=0;
					s.pop();
				}
				vis[x]=1;
			}
			else vis[x]=1;
            s.push(x);
		}else
			vis[-x]=0;
	}
	cout<<ans<<endl;
	return 0;
}
原文