Problem Description
There is a sequence X (i.e. x[1], x[2], …, x[n]). We define increasing subsequence of X
as x[i1], x[i2],…,x[ik], which satisfies follow conditions:
- x[i1] < x[i2],…,<x[ik];
- 1<=i1 < i2,…,<ik<=n
As an excellent program designer, you must know how to find the maximum length of the
increasing sequense, which is defined as s. Now, the next question is how many increasing
subsequence with s-length can you find out from the sequence X.
For example, in one case, if s = 3, and you can find out 2 such subsequence A and B from X.
- A = a1, a2, a3. B = b1, b2, b3.
- Each ai or bj(i,j = 1,2,3) can only be chose once at most.
Now, the question is:
- Find the maximum length of increasing subsequence of X(i.e. s).
- Find the number of increasing subsequence with s-length under conditions described (i.e. num).
Input
The input file have many cases. Each case will give a integer number n.The next line will
have n numbers.
Output
The output have two line. The first line is s and second line is num.
Sample Input
4
3 6 2 5
Sample Output
2
2
题意:求最长上升子序列,同时求出有多少个序列长度和最大长度相同 |
思路(DP):
前面一步就是模板问题了。因为写的时候不知道数据范围,就用O(nlogn)版的LIS算法写。
第二步求有多少个dp[i] = maxlen的时候,对每个i位置往前找dp[j] , 先找dp[j]=maxlen-1的,再找dp[j]=maxlen-2的,因为当前的len长度肯定是由前面的len-1的位置转移过来的。就这样一直往前找当前len-1的点即可。 记住同时用过的点要标记,因为题目说每个元素只能用一次!
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cmath>
#include <string>
#include <map>
#define maxn 1000000+5
using namespace std;
typedef long long ll;
ll dp[maxn];
ll cur_len[maxn];
ll a[maxn];
int static inf = 0x3f3f3f3f;
int main()
{
ios::sync_with_stdio(false);
ll n;
while(cin>>n)
{
for(int i=1;i<=n;i++)
cin>>a[i];
cur_len[0] = -inf;
cur_len[1] = a[1];
ll maxlen = 1;
for(int i=1;i<=n;i++)
{
ll L = 1, R = maxlen, mid;
if(a[i]>cur_len[maxlen])
{
cur_len[++maxlen] = a[i];
dp[i] = maxlen;
}
else
{
while(L<=R)
{
mid = (L+R)>>1;
if(cur_len[mid]<a[i])
L = mid + 1;
else
R = mid -1;
}
cur_len[L] = a[i];
dp[i] = L;
}
}
cout<<maxlen<<endl;
ll cnt=0;
map<ll,ll> vis;
for(int i=1;i<=n;i++)
if(dp[i]==maxlen) cnt++;
for(int i=1;i<=n;i++)
{
if(dp[i]==maxlen)
{
int flag = 1;
ll curlen = maxlen - 1;
vis[i] = 1;
for(int j=i-1;j>=1;j--)
{
if(curlen==dp[j]&&!vis[j])
{
vis[j] = 1;
curlen --;
}
}
if(curlen) cnt--;
}
}
cout<<cnt<<endl;
}
return 0;
}