k-flat sequence

k -flat sequence

A sequence {ai } is called k- flat if for any two consecutive elements ai and ai+ 1, the following holds true: |ai - ai+ 1 | k. For a given sequence, find the longest subsequence which is k- flat.

Input : (standard input)

+Line 1 contains two numbers n and k , 1 ( n , k ) 100000, where n denotes a number of elements of a sequence.

+Line 2 contains n positive integers - elements of a given sequence, all of them are not greater than 1000000000.

Output : (standard output)

Your program should print out k- flat subsequence with the maximum length .If there are more than one solution, print the one for which the last element has the smallest index, if there are more than one such solutions, print the one for which the next to last has the smallest index, etc.

Example:

For sample input:

6 3

2 9 7 2 5 8

a correct output format:

9 7 5 8

Hint: There are two 3-flat subsequences (k = 3) with four elements: 9 7 5 8 and 2 2 5 8. Both ends up with the same element (8), the next to last are also the same (5), but 7 is earlier (has smaller index) than 2 in the above example.

solution:

#include <stdio.h> #include <math.h> #include <stack> using namespace std; int data[100001]; int num[100001]; int grp[100001]; int n; int k; void kFlat() { num[0] = 1; grp[0] = 0; for(int i = 1; i < n; i++) { int max = 1; int g = i; for(int j = 0; j < i; j++) { if( abs(data[i] - data[j]) <= k ) { if ( num[j] >= max) { max = num[j] + 1; g = j; } } } num[i] = max; grp[i] = g; } int maxIndex = 0; int maxValue = 0; for(int i = 0; i < n; i++) { if(num[i] > maxValue) { maxValue = num[i]; maxIndex = i; } } stack<int> s; do { s.push(data[maxIndex]); maxIndex = grp[maxIndex]; maxValue--; } while(maxValue > 0); while(!s.empty()) { printf("%d ", s.top()); s.pop(); } printf("/n"); } int main() { scanf("%d %d", &n, &k); for(int i = 0; i < n; i++) { scanf("%d", &(data[i])); } kFlat(); return 0; }

说明:数据和是正确的, 但是序列打印有问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值