2022牛客多校1 A Villages: Landlines

题意

https://ac.nowcoder.com/acm/contest/33186/A

\(n\)个区间,问把所有区间连起来的长度

解法

很简单,按照左端点排序后用右端点更新,如果当前左端点不在已经覆盖到的范围内则更新答案。

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cctype>
#include<queue>
#define ll long long
#define gc getchar
#define maxn 200005
using namespace std;

inline ll read(){
	ll a=0;int f=0;char p=gc();
	while(!isdigit(p)){f|=p=='-';p=gc();}
	while(isdigit(p)){a=(a<<3)+(a<<1)+(p^48);p=gc();}
	return f?-a:a;
}int n,pre,ans;

struct ahaha{
	int l,r;
	inline bool friend operator<(const ahaha x,const ahaha y){
		if(x.l==y.l)return x.r>y.r;
		return x.l<y.l;
	}
}a[maxn];

int main(){
	n=read();
	for(int i=1;i<=n;++i){
		int x=read(),d=read();
		a[i].l=x-d,a[i].r=x+d;
	}
	sort(a+1,a+n+1);
	pre=a[1].r;
	for(int i=2;i<=n;++i){
		if(a[i].l>pre)
			ans+=a[i].l-pre;
		pre=max(pre,a[i].r);
	}
	printf("%d\n",ans);
	return 0;
}
posted @ 2022-07-18 20:44  子谦。  阅读(17)  评论(1编辑  收藏  举报
Live2D
//雪