P2782 友好城市
题目链接:
思路:
我们可以先对河岸一边从小到大排序,对于另外一边,就转换为求最长上升子序列的问题了。
二分+贪心代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+10;
int n;
struct edge{
int x, y;
}p[N];
//g[i] 表示长度为i的子序列最后数字
int len = 1, g[N];
//sort判断函数
bool cmp(edge a, edge b){
return a.x < b.x;
}
int main(){
cin >> n;
//读入
for(int i = 1; i <= n; i++){
cin >> p[i].x >> p[i].y;
}
//对p根据x从小到大排序
sort(p+1, p+1+n, cmp);
//对p[i]选出最长上升子序列
g[1] = p[1].y;
for(int i = 2; i <= n; i++){
//当满足上升 添加到g[]中
if(g[len] <= p[i].y){
g[++len] = p[i].y;
}
else{//不满足
int l = 0, r = len+1;
while(l+1 < r){
int mid = (l+r) / 2;
if(g[mid] < p[i].y){
l = mid;
}
else r = mid;
}
g[r] = p[i].y;
}
}
cout << len << endl;
return 0;
}