Description
Now give you a number sequence Ai, you need to calculate the longest length of subsequence Bi, meet the requirements of Bi & Bi-1 is not equal to zero. (2<=i<= len).
Input
Input contain two lines, The first line contains a number n, The second line continues n integers, which representation Ai, n <=100000, ai<= 2 * 10^9.
Output
Output contain one line, output the length of longest subsequence Bi satisfying the requirements.
Sample Input
3 1 2 3
Sample Output
2
题意:给定一个长度为n的数列ai,求ai的子序列bi的最长长度,满足bi&bi-1!=0 (2<=i<=n)。(不一定是连续的啊。。)
思路:既然要求此项和前一项&不为0,我们知道当两个数所对应的二进制中相同位都为1,那么这两个数相与才一定不为0;
这里我们dp记录二进制中所对应的1的当前序列的最长值,找出最长序列记得要把这个数的三个位置都变成最长的长度,
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int dp[32];
int main()
{ int n,i,x;
scanf("%d",&n);
int res=1,ans=1;;
while(n--)
{ scanf("%d",&x);
res=1;
for(i=0;i<=30;i++)//一共32位;
{ if(x&1<<i)
res=max(res,dp[i]+1);//找到一个为1长度就+1,并记录最长的
}
ans=max(ans,res);
for(i=0;i<=30;i++)
{ if(x&1<<i)
dp[i]=res;//找到最长长度将所有为1的都更新为最长长度;因为只需要对应一个二进制是相同的1就可以符合条件;
}
}
printf("%d\n",ans);
return 0;
}