题解 CF527D 【Clique Problem】
NaCly_Fish · · 题解
这题的解法分为三步进行,
Step 1:读懂题意
对于两个点
然后要求出最大团中点的数量。注意这里团的定义是两两点之间都有边的顶点集合,也就是每一对点之间都有边。
Step 2:分析原式
由于连边是双向的,所以每一对点我们只用考虑一次。所以这里我们设
对于一个点
然后再回头看看刚才推出来的式子,就变成了
Step 3:转化问题
由此我们可以联想到什么?没错,就是线段覆盖。
我们可以把每个点都看成是
所以题目中给的问题,实际上就是从数轴上的一些线段中取尽可能多,使其互不重叠,也就是线段覆盖问题。这个经典问题贪心就可以解决,原题目可以看 P1803,在这里就不多做讲解了。
参考代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
#define N 200003
using namespace std;
struct node{
//定义结构体,存储一个点
int l,r;
node(int l=0,int r=0):l(l),r(r){}
bool operator < (const node& nd) const{
//重载运算符,线段覆盖排序用。以r为第一关键字,
//l为第二关键字,从小到大排序
if(r!=nd.r) return r < nd.r;
return l < nd.l;
}
};
int n;
node a[N];
inline void read(int &x){
//喜闻乐见的快读
x = 0;
char c = getchar();
while(!isdigit(c)) c = getchar();
while(isdigit(c)){
x = (x<<3)+(x<<1)+c-'0';
c = getchar();
}
}
int main(){
int l,r,n,x,w,ans = 0;
read(n);
for(int i=1;i<=n;++i){
read(x),read(w);
a[i] = node(x-w,x+w);
//x-w 和 x+w 对应上述的l和r
}
sort(a+1,a+1+n);
//按照定义的规则排序
r = -inf;
//初始设当前右端点为 -inf,防止出现问题
for(int i=1;i<=n;++i){
if(a[i].l<r) continue;
//左端点比当前右端点小,肯定会重叠,跳过
++ans;
//不会重叠,答案++
r = a[i].r;
//更新右端点
}
printf("%d",ans);
return 0;
}