ZigZag - 2003 TCCC Semifinals 3

来源:互联网 发布:找不到男朋友 知乎 编辑:程序博客网 时间:2024/06/07 20:38



Problem Statement

    
A sequence of numbers is called a zig-zag sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a zig-zag sequence.

For example, 1,7,4,9,2,5 is a zig-zag sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, 1,4,7,2,5 and 1,7,4,5,5 are not zig-zag sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, sequence, return the length of the longest subsequence of sequence that is a zig-zag sequence. A subsequence is obtained by deleting some number of elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. 


动态规划。

状态:

令d[i]为前i个数中以num[i]为结尾的最长的zigzag数序列长度。

状态转移方程:

要求d[i],就是把i前面的各个子序列中(0<=j<i),最后一个数(即num[j])与num[i]满足zigzag的序列长度加1(即d[j]+1),然后取最大的长度即为d[i]。如果,i前面的所有子序列的最后一个数和num[i]都不满足zigzag要求,则d[i]为0。


int longestZigZag(int num[], int n){    int *d = new int[n];    int *label = new int[n];    int max_len = 1;    d[0] = 1;    label[0] = 0;    for(int i = 1; i < n; i++)    {        d[i] = 0;        for(int j = 0; j < i; j++)        {            if(num[i] < num[j] && label[j] >= 0 && d[j] + 1 > d[i])            {                d[i] = d[j] + 1;                label[i] = -1;            }            else if(num[i] > num[j] && label[j] <= 0 && d[j] + 1 > d[i])            {                d[i] = d[j] + 1;                label[i] = 1;            }            else                continue;        }        if(d[i] > max_len)            max_len = d[i];    }    delete[] d;    delete[] label;    return max_len;}


 

0 0
原创粉丝点击