The All-purpose Zero
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1950 Accepted Submission(s): 920
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.
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: 5
HintIn the first case,you can change the second 0 to 3.So the longest increasing subsequence is 0 1 2 3 5.
Author
FZU
Source
2016 Multi-University Training Contest 4
题意:
有n个非负整数,其中0可以变成任意的其他数,问你最长上升子序列的长度为多少?
分析:
题目说0可以变成任意数,包括负数。。。我就是被这个坑了好久。。。
由于0可以变成任意数,所以在最后的子序列中一定包括所有的0.
对于任意s[i],它前面的0的个数为num,那么前i个数的最长上升子序列最小长度为num + 1
比如 … 0 0 s[i],为了满足最优性那么序列会变成 … s[i]-2,s[i]-1,s[i]
那么s[i] 前面的非0的数s[j]要加在序列中,那么一定有s[j] < s[i] - num
所以我们将所有的非0数减去它前面的0的个数后,在求最长上升子序列的长度+0的个数即可
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 100010;
int s[maxn];
int main()
{
int t,n,cas=1;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int m = 0,num = 0;
for(int i=0;i<n;i++)
{
scanf("%d",&s[i]);
if(!s[i]) num++;
else s[m++] = s[i] - num;
}
int pos,len = 0;
for(int i=0;i<m;i++)
{
pos = lower_bound(s,s+len,s[i]) - s;
s[pos] = s[i];
if(pos == len) len++;
}
printf("Case #%d: %d\n",cas++,len + num);
}
return 0;
}