The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Print a single number — the number of vertexes in the maximum clique of the given graph.
4 2 3 3 1 6 1 0 2
3
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
题意:给在一维坐标上给一系列点,点有两个参数:坐标xi,权wi,当两点间满足|xi-xj|>=wi+wj 那么两点间可连一条无向边,求最大集,使点集中任意两点间有边相连
思路: 对|xi-xj|>=wi+wj 分析,当加入一个点到最大集中,这个点与任何点均满足这个关系,所以试图发现这个不等关系的传递性。
可构造这样的模型,把每个点的参数改成(Xi,Yi)=(xi-wi,xi+wi),当满足Xj>Yi 的时候说明i与j之间可以连边
所以如何当把j点加入的最大集的时候要满足Xj>Yi&&Xj>Yi'&&Xj>Yi''&&....( 即对最大集的其他所有点均有Xj>Yi的关系)
所以可以把点先按{Xi}排序,当Xj>Yi的时候,加入到最大集中,且关系可以传递到其他点,所以所有点均有边
复杂度线性
//GNU C++ Accepted 93 ms 3616 KB #include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<vector> using namespace std; typedef pair<int,int >pii; vector<pii> all; int main() { int n,ans=0; cin>>n; for(int i=1;i<=n;i++) { int x,w; scanf("%d%d",&x,&w); all.push_back(pii(x-w,x+w)); } sort(all.begin(),all.end()); int last=-0x3f3f3f3f; for(vector<pii>::iterator it = all.begin();it!=all.end();it++) { if(last<=(*it).first ) last = (*it).second,ans++; else if(last>(*it).second) last=(*it).second;//贪心替换上一个点 } cout<<ans<<endl; return 0; }