题目链接:友好城市 - 洛谷
思路:对两组河东河西的坐标,如果x1>x2,但y1<y2则会交叉。所以可以将n对城市按x排序,求y的最长上升子序列。
dp法:(超时)
#include<iostream>
#include<algorithm>
using namespace std;
struct Address
{
int a,b;
bool operator<(const Address x)const{
return a<x.a;
}
};
Address a[200005];
int f[200005];
int ans=0;
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;++i)
{
cin>>a[i].a>>a[i].b;
}
sort(a+1,a+n+1);
for(int i=1;i<=n;++i)
{
f[i]=1;
for(int j=1;j<i;++j)
{
if(a[i].b>a[j].b) f[i]=max(f[i],f[j]+1);
}
ans=max(ans,f[i]);
}
cout<<ans<<endl;
return 0;
}
贪心+二分法:
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 200005;
struct city
{
int x,y;
bool operator<(const city a)const {
return x<a.x;
}
};
city c[MAXN];
int a[MAXN];
int dp[MAXN];
int cnt=0;
int main()
{
int n;
cin>>n;
for(int i=0;i<n;++i)
{
cin>>c[i].x>>c[i].y;
}
sort(c,c+n);
for(int i=0;i<n;++i)
{
a[i]=c[i].y;
}
dp[0]=a[0];
for(int i=1;i<n;++i)
{
if(a[i]>dp[cnt]) dp[++cnt]=a[i];
else
{
dp[lower_bound(dp,dp+cnt+1,a[i])-dp]=a[i];
}
}
cout<<cnt+1<<endl;
return 0;
}