您的位置:首页 > 其它

LIS(最长递增子序列) Zigzag

2017-07-08 00:24 344 查看
#include<cstdio>
int main()
{
int length=10;
int array[10],result[10];
unsigned int i, j, k, max;

//变长数组参数,C99新特性,用于记录当前各元素作为最大元素的最长递增序列长度
unsigned int liss[length];

//前驱元素数组,记录当前以该元素作为最大元素的递增序列中该元素的前驱节点,用于打印序列用
unsigned int pre[length];

for(i = 0; i < length; ++i)
{
liss[i] = 1;
pre[i] = i;
}
array[0]=1;
array[1]=5;
array[2]=3;
array[3]=2;
array[4]=7;
for(i = 1, max = 1, k = 0; i < length; ++i)
{
//找到以array[i]为最末元素的最长递增子序列
for(j = 0; j < i; ++j)
{
//如果要求非递减子序列只需将array[j] < array[i]改成<=,
//如果要求递减子序列只需改为>
if(array[j] < array[i] && liss[j] + 1> liss[i])
{
liss[i] = liss[j] + 1;
pre[i] = j;

//得到当前最长递增子序列的长度,以及该子序列的最末元素的位置
if(max < liss[i])
{
max = liss[i];
k = i;
}
}
}
}

//输出序列
i = max - 1;

while(pre[k] != k)
{
result[i--] = array[k];
k = pre[k];
}

result[i] = array[k];
for(int i=0;i<10;i++)
{
printf("%d ",result[i]);
}
//return max;
}




题意:Z字型。 要么上下 要么下上进行递增或递减。

#include<bits/stdc++.h>
using namespace std;

#define pi acos(-1)
#define endl '\n'
#define rand() srand(time(0));
#define me(x) memset(x,0,sizeof(x));
#define foreach(it,a) for(__typeof((a).begin()) it=(a).begin();it!=(a).end();it++)
#define close() ios::sync_with_stdio(0);

typedef long long LL;
const int INF=0x3f3f3f3f;
const LL LINF=0x3f3f3f3f3f3f3f3fLL;
//const int dx[]={-1,0,1,0,-1,-1,1,1};
//const int dy[]={0,1,0,-1,1,-1,1,-1};
const int maxn=1e4+5;
const int maxx=1e6+100;
const double EPS=1e-7;
const int MOD=10000007;
typedef pair<int, int>P;
#define mod(x) ((x)%MOD);
template<class T>inline T min(T a,T b,T c) { return min(min(a,b),c);}
template<class T>inline T max(T a,T b,T c) { return max(max(a,b),c);}
template<class T>inline T min(T a,T b,T c,T d) { return min(min(a,b),min(c,d));}
template<class T>inline T max(T a,T b,T c,T d) { return max(max(a,b),max(c,d));}
//typedef tree<pt,null_type,less< pt >,rb_tree_tag,tree_order_statistics_node_update> rbtree;
/*lch[root] = build(L1,p-1,L2+1,L2+cnt);
rch[root] = build(p+1,R1,L2+cnt+1,R2);中前*/
/*lch[root] = build(L1,p-1,L2,L2+cnt-1);
rch[root] = build(p+1,R1,L2+cnt,R2-1);中后*/
long long gcd(long long a , long long b){if(b==0) return a;a%=b;return gcd(b,a);}
#define FOR(x,n,i) for(int i=x;i<=n;i++)
#define FOr(x,n,i) for(int i=x;i<n;i++)
#define W while

int a[maxn];
int dp[maxn][2];

int main()
{
FOR(1,maxn,i)
FOR(0,1,j)
dp[i][j]=1;
int n;
cin>>n;
FOR(1,n,i)
cin>>a[i];
int ans=0;
FOR(1,n,i)
{
FOR(1,i,j)
{
if(a[i]>a[j])
dp[i][0]=max(dp[j][1]+1,dp[i][0]);
if(a[i]<a[j])
dp[i][1]=max(dp[j][0]+1,dp[i][1]);
}
ans=max(dp[i][0],dp[i][1],ans);
}
cout<<ans<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: