跳到正文

题解

P14121 题解

wukaichen888约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年10月2日
收录
2025年12月12日
更新
2026年11月12日
篇幅
约 2 分钟
题目
P14121

版本

  1. v2当前
  2. v1

一道比较喜欢的题。

考虑贪心所以只加入 x→x+1x\to x+1 连边不劣。

考虑当前已顺次遍历 1∼x1\sim x,设 max⁡i\max_i 为 ii 邻域最大编号点。对于点 i∈[1,x]i\in[1,x],max⁡i>x\max_i\gt x 则点 ii 必然在 dfs 栈中,max⁡i≤x\max_i\le x 则点 ii 无贡献。

考虑直接找到最靠后的 max⁡i>x\max_i\gt x 点判断其是否与 x+1x+1 相邻即可。

C++
#pragma target("avx512f,sse2,sse3,sse4,sse4.2")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll N=1e6+5,inf=1e6;
int t,n,m;
int stk[N],top,ans,maxx[N],vis[N];
vector<int>v[N];
void work(){
	stk[top=1]=1; ans=0;
	for(int now=2;now<=n;now++){
		for(int to:v[now]) vis[to]=1;
		while((top>=2)&&(maxx[stk[top]]<=now-1)) top--;

		if(!vis[stk[top]]) ans++;
		stk[++top]=now;

		for(int to:v[now]) vis[to]=0;
	}
	printf("%d\n",ans);
}
signed main(){
	scanf("%d",&t);
	while(t--){
		scanf("%d%d",&n,&m);
		for(int i=1,x,y;i<=m;i++){
			scanf("%d%d",&x,&y);
			v[x].push_back(y);
			v[y].push_back(x);
			maxx[x]=max(maxx[x],y);
			maxx[y]=max(maxx[y],x);}
		work();
		for(int i=1;i<=n;i++) v[i].clear(),maxx[i]=0;
	}
	return 0;
}


原文