The All-purpose Zero
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1603 Accepted Submission(s): 770
Problem Description
?? gets an sequence S with n intergers(0 < n <= 100000,0<= S[i] <= 1000000).?? has a magic so that he can change 0 to any interger(He does not need to change all 0 to the same interger).?? wants you to help him to find out the length of the longest increasing (strictly) subsequence he can get.
Input
The first line contains an interger T,denoting the number of the test cases.(T <= 10)
For each case,the first line contains an interger n,which is the length of the array s.
The next line contains n intergers separated by a single space, denote each number in S.
For each case,the first line contains an interger n,which is the length of the array s.
The next line contains n intergers separated by a single space, denote each number in S.
Output
For each test case, output one line containing “Case #x: y”(without quotes), where x is the test case number(starting from 1) and y is the length of the longest increasing subsequence he can get.
Sample Input
2 7 2 0 2 1 2 0 5 6 1 2 3 3 0 0
Sample Output
Case #1: 5 Case #2: 5HintIn the first case,you can change the second 0 to 3.So the longest increasing subsequence is 0 1 2 3 5.
题意:给出一个n个数字的数列,数列中零可以变成任意数,也可以是负数,问最长上升子序列的长度是多少?
题解:求LIS的最大长度时一定要把所有的零放进去,例如3 0 4 这种情况可以把变为 3 4 4,最优解长度依然是2。
对于 L 0 R(R>L+1)这种情况0就可以变成中间任意的数了。
注意
重点理解
部分:把不是0的数都减去前面0出现的个数,组成一个新的数组。(因为遇到0,0的个数num++,continue了。构成的一个新数组没有0组成也就少了之前0的个数)。在对新的数组进行查询最长上升子序,加上num即可。
这里查询最长上升子序列用新的方法挺简单的:dp[ ]里的每个元素就是a[ i ]的最长上升子序列。
最长上升子序列的长度也可以用已知二分公式快速求出。
<span style="font-size:10px;">#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define CLR(a,b) memset(a,b,sizeof(a))
int dp[100010];
int main()
{
int u,ca=1;
scanf("%d",&u);
while(u--)
{
int n;
int a[100010];
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
int num=0,ant=0;
for(int i=0;i<n;i++)
{
if(a[i]==0)
{
num++;
continue; //继续,所以下面新序列a[i]数组元素数目减少
}
a[i]-=num;
a[ant++]=a[i]; //减去0后构成的新的序列
}
fill(dp,dp+ant,INF);
for(int i=0;i<ant;i++)
*lower_bound(dp,dp+ant,a[i])=a[i]; //构成一个新的数组dp[],这个数组里的元素是新的a[i]的最长上升子序列
printf("Case #%d: %d\n",ca++,lower_bound(dp,dp+ant,INF)-dp+num); //最长上升子序列长度+num就是结果
}
return 0;
}
</span>