51nod 1376 最长递增子序列的数量(dp+cdq分治)

51nod 1376 最长递增子序列的数量(dp+cdq分治)

数组A包含N个整数(可能包含相同的值)。设S为A的子序列且S中的元素是递增的,则S为A的递增子序列。如果S的长度是所有递增子序列中最长的,则称S为A的最长递增子序列(LIS)。A的LIS可能有很多个。例如A为:{1 3 2 0 4},1 3 4,1 2 4均为A的LIS。给出数组A,求A的LIS有多少个。由于数量很大,输出Mod 1000000007的结果即可。相同的数字在不同的位置,算作不同的,例如 {1 1 2} 答案为2。

Input

第1行:1个数N,表示数组的长度。(1 <= N <= 50000)
第2 - N + 1行:每行1个数A[i],表示数组的元素(0 <= A[i] <= 10^9)

Output

输出最长递增子序列的数量Mod 1000000007。
Input示例
5
1
3
2
0
4
Output示例
2

题解:

这题的做法有很多,我就拿来练练cdq分治。
分治的套路:
  第一维排序,第二维分治
  1. 先递归求解区间左半边
  2. 用左边的值更新右边,相当于处理跨越区间中点的情况
  3. 递归求解区间右半边

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5+5;
const int mod=1e9+7; 
int a[maxn];
int idx[maxn];
typedef pair<int,int> P;
P f[maxn];
bool cmp(int x,int y)
{
	return a[x]==a[y]?x>y:a[x]<a[y];
}
void Max(P& x, P y)
{
	if(x.first==y.first)
	{
		x.second=(x.second+y.second)%mod;
	}
	else if(x.first<y.first) x=y;
}
void cdq(int l,int r)
{
	if(l==r) return;
	int m=(l+r)>>1;
	cdq(l,m);
	for(int i=l;i<=r;i++) idx[i]=i;
	sort(idx+l,idx+r+1,cmp);
	P _max(0,0);
	for(int i=l;i<=r;i++)
	{
		int index=idx[i];
//		cout<<index<<endl;
		if(index<=m)
		{
			Max(_max,f[index]) ;
		}
		else
		{
			P temp=_max;
			temp.first+=1; 
			Max(f[index],temp);
		}
	 } 
	 cdq(m+1 ,r); 
 } 
int main()
{
	int T,n,m,i,j,k;
	scanf("%d",&n);
	for(i=1;i<=n;i++) scanf("%d",&a[i]);
	for(i=1;i<=n;i++)f[i]=P(1,1) ;
	cdq(1,n);
	P ans(0,0);
	for(int i=1;i<=n;i++) Max(ans,f[i]);
	 printf("%d\n",ans.second);
}

猜你喜欢

转载自blog.csdn.net/weixin_40859716/article/details/82502215
今日推荐