HDU 5748 Bellovin(dp+二分)

来源:互联网 发布:安装win7无法连接网络 编辑:程序博客网 时间:2024/05/29 12:38

Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)

Problem Description

Peter has a sequence a1,a2,…,an and he define a function on the sequence – F(a1,a2,…,an)=(f1,f2,…,fn), where fi is the length of the longest increasing subsequence ending with ai.

Peter would like to find another sequence b1,b2,…,bn in such a manner that F(a1,a2,…,an) equals to F(b1,b2,…,bn). Among all the possible sequences consisting of only positive integers, Peter wants the lexicographically smallest one.

The sequence a1,a2,…,an is lexicographically smaller than sequence b1,b2,…,bn, if there is such number i from 1 to n, that ak=bk for 1≤k< i and ai< bi.

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first contains an integer n (1≤n≤100000) – the length of the sequence. The second line contains n integers a1,a2,…,an (1≤ai≤109).

Output

For each test case, output n integers b1,b2,…,bn (1≤bi≤109) denoting the lexicographically smallest sequence.

Sample Input

3
1
10
5
5 4 3 2 1
3
1 3 5

Sample Output

1
1 1 1 1 1
1 2 3

Source

BestCoder Round #84


问题分析

经典的LIS问题,即求数列前i(1in)项的LIS的长度。一开始使用dp[i]直接保存结果,时间复杂度为O(x2),果断超时。后来查询资料得到,可以使用dp[i]保存LIS长度为i的子列的最后一个数,并使这个数尽量小,length表示dp数组的长度。具体的实现方法是先将所有数据读入到a数组中,对于每个a[i],使用C++STL中的lower_bound找到dp数组中第一个比a[i]大的数字的位置,如a[i]已是dp数组中的最大数,则直接放到dp数组的末尾,相应的dp数组的length加一,否则用a[i]直接替换位置上的数,res表示插入数在dp数组中的位置,可直接输出。时间复杂度为O(nlogn)。

AC代码

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>#include<cmath>#include<vector>#define ull unsigned long long#define rep(i,a,b) for (int i=(a),_ed=(b);i<=_ed;i++)#define rrep(i,a,b) for(int i=(a),_ed=(b);i>=_ed;i--)#define fil(a,b) memset((a),(b),sizeof(a))#define cl(a) fil(a,0)#define PI 3.1415927#define inf 0x3f3f3f3fusing namespace std;int a[100005];int dp[100005];int main(void){    int T,n,*pos=a,length,res;    cin >> T;    while (T--)    {        fil(dp, inf);        cin >> n;        rep(i, 1, n) scanf("%d", &a[i]);        if (n == 1) cout << 1 << endl;        else        {            dp[1] = a[1];            length = 1;            res = 1;            cout << 1 << " ";            rep(i, 2, n)            {                if (a[i] > dp[length])                {                    dp[length + 1] = a[i];                    length++;                    res = length;                }                else                {                    pos = lower_bound(dp+1, dp + length+1, a[i]);                    *pos = a[i];                    res = pos - dp;                }                if(i!=n) cout << res << " ";                else cout << res;            }            cout << endl;        }    }    return 0;}

第一篇博客,初次使用markdown。
2016 年 09月 13日

0 0
原创粉丝点击