ZOJ 2319 Beautiful People (LIS的变形)

本文探讨了一个涉及复杂关系的最长上升子序列问题,通过将输入数据按照特定规则排序,进而求解最长上升子序列的长度,并提供了一个高效的O(nlogn)算法实现。详细介绍了排序策略、动态规划的使用以及最终构造路径的方法。

题目大意

  • 有n个人的,每个人有一个si和bi,对于i和j来说,只有当si < sj && bi < bj ,或者 si > sj && bi > bj 时,二人才不会互相讨厌。
  • 也就是说,只有两个人其中一方的s和b都小于另一方时,二人才不会互相讨厌。
  • 求最多有多少人不会互相讨厌

分析

  • 给n个人按s排序从小到大,若s相等则按b从大到小排序。
  • 然后求b的最长上升子序列的长度ans即可
  • 用O(nlogn)的算法
  • 最后再按照ans构造路径

代码

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;
#define INF 0x7fffffff
const int maxn = 1e5+10;
struct Node {
    int s , b;
    int id;
    bool operator < (const Node &rhs) const {
        return (s < rhs.s) || (s == rhs.s && b > rhs.b);
    }
}node[maxn];
int dp[maxn]; //dp[i]表示以i结尾的最长上升子序列的长度
int g[maxn];  //g[i]表示dp值为i的最小状态值
int rel[maxn];

int main()
{
    int t , n;
    cin >> t;
    while(t--)
    {
        cin >> n;
        for(int i = 0; i < n; i++) {
            cin >> node[i].s >> node[i].b;
            node[i].id = i + 1;
        }
        sort(node , node + n);
        for(int i = 1; i <= n; i++) g[i] = INF;

        for(int i = 0; i < n; i++) {
            int k = lower_bound(g+1 , g+1+n , node[i].b) - g;
            dp[i] = k;
            g[k] = node[i].b;
        }

        int ans = dp[0] , cnt = 0;;
        for(int i = 1; i < n; i++) ans = max(ans , dp[i]);
        cout << ans << endl;
        for(int i = n-1; i >= 0; i--) if(ans == dp[i]) {
            rel[cnt++] = node[i].id;
            ans--;
        }
        for(int i = cnt - 1; i > 0; i--) cout << rel[i] << " ";
        cout << rel[0] << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值