codeforces 340D Bubble Sort Graph(dp+二分)

Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).

procedure bubbleSortGraph()
    build a graph G with n vertices and 0 edges
    repeat
        swapped = false
        for i = 1 to n - 1 inclusive do:
            if a[i] > a[i + 1] then
                add an undirected edge in G between a[i] and a[i + 1]
                swap( a[i], a[i + 1] )
                swapped = true
            end if
        end for
    until not swapped 
    /* repeat the algorithm as long as swapped value is true. */ 
end procedure

For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.

Input

The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1a2, ..., an (1 ≤ ai ≤ n).

Output

Output a single integer — the answer to the problem.

Example
Input
3
3 1 2
Output
2
Note

Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].

 

  
/*
 这题题意比较难懂,冒泡排序,每交换一次就在图中建一条边,最终要求图中没有直接边相连的点集个数最大值
 如果i<j && a[i]>a[j]就要交换,所以逆序对之间一定有边 所以这题就转化成求非逆序对个数了,很明显就是求最长非递减子序列了 
 但是题目数据量较大  所以要用二分法
 详见代码
*/

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1e5+4;
int m,n;
int a[N];
int dp[N];
int cnt;

int LIS()
{
    cnt=0;
    int pos;
    for(int i=1;i<=m;i++)
    {
        if(a[i]>=dp[cnt])dp[++cnt]=a[i];
        else
        {
            pos= upper_bound(dp,dp+cnt+1,a[i])-dp;//找到第一个大于a[i]的值,返回其下标
            dp[pos]=a[i]; //把这个值替换成a[i] ps: 这样是不影响最终不下降子序列长度的
        }
    }
}

int main()
{
    scanf("%d",&m);
    dp[0]=0;//初始化为0
    for(int i=1;i<=m;i++)
    {
        scanf("%d",&a[i]);
        dp[i]=0;
    }
    LIS();
    printf("%d\n",cnt);
    return 0;
}

/*
7
2 3 3 5 3 2 4

5
*/


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值