Codeforces Round #649 (Div. 2) B. Most socially-distanced subsequence

Codeforces Round #649 (Div. 2) B. Most socially-distanced subsequence

题目链接
Given a permutation p of length n, 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 p 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 a 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.

Input

The first line contains an integer t (1≤t≤2e4) — 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≤1e5) — the length of the permutation p.

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

The sum of n across the test cases doesn’t exceed 1e5.

Output

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.

Example

input

2
3
3 2 1
4
1 3 4 2

output

2
3 1 
3
1 4 2 

这题个人觉得比较有意思~
首先对三个数 s 1 , s 2 , s 3 s_1,s_2,s_3 s1,s2,s3 我们不难发现,当 s 1 < s 2 < s 3 s_1s1<s2<s3 s 1 > s 2 > s 3 s_1>s_2>s_3 s1>s2>s3 时, ∣ s 1 − s 2 ∣ + ∣ s 2 − s 3 ∣ = ∣ s 1 − s 3 ∣ |s_1−s_2|+|s_2−s_3|=|s_1-s_3| s1s2+s2s3=s1s3,当类推到 n n n 个数时也是如此~
所以最优解就是一大一小交替存储数组中的值即可,AC代码如下:

#include
using namespace std;
typedef long long ll;
main(){
    int t;
    cin>>t;
    while(t--){
        int n,x,siz=0;
        cin>>n;
        vector<int>ans;
        for(int i=0;i<n;i++){
            cin>>x;
            if(ans.empty()||siz==1) ans.push_back(x),siz++;
            else{
                if(ans[siz-2]<ans.back()&&ans.back()<x) ans.pop_back(),ans.push_back(x);
                else if(ans[siz-2]>ans.back()&&ans.back()>x) ans.pop_back(),ans.push_back(x);
                else ans.push_back(x),siz++;
            }
        }
        cout<<ans.size()<<endl;
        for(auto i:ans) cout<<i<<" ";
        puts("");
    }
}

你可能感兴趣的:(思维,贪心,Codeforces)