Description
Peter has a sequence
and he define a function on the sequence --
, where
is the length of the longest increasing subsequence ending with
.
Peter would like to find another sequence in such a manner that equals to . Among all the possible sequences consisting of only positive integers, Peter wants the lexicographically smallest one.
The sequence is lexicographically smaller than sequence , if there is such number from to , that for and .
Peter would like to find another sequence in such a manner that equals to . Among all the possible sequences consisting of only positive integers, Peter wants the lexicographically smallest one.
The sequence is lexicographically smaller than sequence , if there is such number from to , that for and .
Input
There are multiple test cases. The first line of input contains an integer
, indicating the number of test cases. For each test case:
The first contains an integer -- the length of the sequence. The second line contains integers .
The first contains an integer -- the length of the sequence. The second line contains integers .
Output
For each test case, output
integers
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题意:
给出一个序列,求出以每个元素结尾的最长子序列的长度,然后找一个字典序最小的这个函数值相同的子序列。
思路:
定义一个数组,初始化都为最大值。再循环输入的数。找到数组中第一个比a大的数,记录下标即可。求完这个值后这个值构成的序列就是这个字典序最小的序列了;
求以a结尾的最长上升子序列的长度用k=lower_bound(dp,dp+n,a)-dp,
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int dp[100010];
#define INF (1<<31-1)//定义INF为0x3f3f3f时会wa;以后还是定义成这个吧;
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
dp[i]=INF;
}
for(int j=0;j<n;j++)
{
int a;
scanf("%d",&a);
int k=lower_bound(dp,dp+n,a)-dp;//找到以a为结尾的最长递增子序列的长度;
if(j==0)
{
printf("%d",k+1);//直接输出长度,要+1因为dp是从0开始的;
}
else
{
printf(" %d",k+1);
}
dp[k]=a;//把找过的这个数放到dp的这个位置中以便下一次寻找另一个数;
}
printf("\n");
}
return 0;
}