洛谷 P2782 友好城市

题目链接:友好城市 - 洛谷

思路:对两组河东河西的坐标,如果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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值