CodeForces #649 B. Most socially-distanced subsequence(思维、规律)

Most socially-distanced subsequence

题目大意:(文末原题)

给出一个长度为n的数组整型数组,输出使 相邻项的差 的绝对值 的和 最大,数组长度最小 的字串及其长度;

思路:

我们通过一个分析一个例子来得出思路

例:

       (1, 2, 3, 8, 7, 11, 13) 的 邻间项差的和是 1 + 1 + 5 + 1 + 4 + 4 = 2 + 5 + 1 + 8;

我们不难理解,不论如何删去项,我们所得的 邻间项差的和 总是小于等于n个数间的 邻间项差的和,所以只需判断如何去项能去掉最多的项,并且保持和不变;我们可以看粗 1 2 3 间的邻间项差的和是 2 = 3 -1;中间的2对结果并没有影响,同理也能看出 7 11 13也满足,但是 3 8 7间却不满足;所以说,只有中间的数夹在两边的数直接,这个数才对结果没有影响,可以删去,所以运用循环判断,计数,并标记是否能输出。

代码:

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

const int maxn = 2e5 + 10;

int a[maxn], vis[maxn];		//vis来标记能否输出 

int main() {
	int t;
	cin >> t;
	
	while(t--) {
		int n, t;
		cin >> n, t = n;
		memset(vis, 0, sizeof(vis));
		
		for(int i = 0; i < n; i++) {	 
			cin >> a[i];
		}
		
		for(int i = 1; i < n - 1; i++) {     //判断是否是夹在中间 
			if((a[i] >= a[i - 1] && a[i] <= a[i + 1]) || (a[i] >= a[i + 1] && a[i] <= a[i - 1])) {
				vis[i]++;
				t--;
			}
		}
		
		cout << t << endl;
		
		for(int i = 0; i < n; i++) {
			if(!vis[i]) {
				if(i == 0) cout << a[i];
				else cout << " " << a[i];
			}
		}
		
		cout << endl;
	}
	
	return 0;
}

原题:

原题:

Given a permutation pp of length nn , find its subsequence s1 , s2 , …… , sk of length at least 2 such that:

  • |s1−s2|+|s2−s3|+…+|sk−1 − sk|is as big as possible over all subsequences of pp with length at least 2 .
  • Among all such subsequences, choose the one whose length, k , is as small as possible.

If multiple subsequences satisfy these conditions, you are allowed to find any of them.

A sequence aa is a subsequence of an array b if a can be obtained from b by deleting some (possibly, zero or all) elements.

A permutation of length n is an array of length n in which every element from 1 to n occurs exactly once.

输入:

The first line contains an integer t (1≤t≤2⋅10^4) — the number of test cases. The description of the test cases follows.

The first line of each test case contains an integer n (2≤n≤10^5) — the length of the permutation p.

The second line of each test case contains n integers p1, p2, ……, pn(1≤pi≤n1, pipi are distinct) — the elements of the permutation p.

The sum of nn across the test cases doesn't exceed 10^5

输出:

For each test case, the first line should contain the length of the found subsequence, k. The second line should contain s1, s2, ……, sk — its elements.

If multiple subsequences satisfy these conditions, you are allowed to find any of them.

样例:

Input:

2
3
3 2 1
4
1 3 4 2

Output:

2
3 1 
3
1 4 2 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值