跳到正文

个人记录

杂题做题记录

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

Problem Description

给定 nn 条线段,在数轴上任选尽可能多的点使得任意两点都存在线段包含一个而不包含另一个。

Idea

先离散化,把答案转化到所有端点上,可以发现端点一定是更优的。答案就是选取端点数量加一。

排序,按点选取。发现左端点必定能被选,考虑右端点何时取到。

发现只有在存在左端点在线段中且右端点在线段外的线段时没有贡献。

注意到每个点最多影响一个点的选取,它影响的点可以代替它影响其他点,所以可以贪心选取。

那么问题来了。。。

怎么计算?

可以用栈记录实际元素个数并延迟删除。

记录栈顶元素,这样可以通过检查元素个数和栈顶是否变化来计算出右端点的贡献。

这也能同样计算左端点贡献。

虽然听起来有点复杂,但代码是简短的。

Accepted
C++
#include<bits/stdc++.h>
using namespace std;
//#define int long long
typedef long long ll;
#define fo(i,l,r) for(int i=l;i<=r;i++)
#define fr(i,l,r) for(int i=l;i>=r;i--)
#define pb push_back
#define fi first
#define se second
#define par pair<int,int>
inline ll rd() {
    ll x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}
const ll N=5e5+5;
int n,k,st[N],pos[N],a[N],top;
map<int,vector<int>>mp;
signed main(){
	int T=rd();while(T--){
		n=rd();fo(i,1,n)mp[rd()].pb(i),mp[rd()+1].pb(-i),a[i]=0;
		k=top=0;int ans=1;
		for(auto v:mp){
			for(auto x:v.se){
				if(x>0)st[++top]=x,pos[x]=top,++k;
				else st[pos[-x]]=0,--k;
			}
			while(top&&st[top]==0)--top;
			ans+=(a[st[top]]!=k);a[st[top]]=k;
		}printf("%d\n",ans);mp.clear();
	}
	return 0;
}
原文