CodeForces #649 B. Most socially-distanced subsequence(思维、规律)
Most socially-distanced subsequence
題目大意:(文末原題)
給出一個長度為n的數(shù)組整型數(shù)組,輸出使 相鄰項的差 的絕對值 的和 最大,數(shù)組長度最小 的字串及其長度;
思路:
我們通過一個分析一個例子來得出思路,
例:
? ? ? ?(1, 2, 3, 8, 7, 11, 13) 的 鄰間項差的和是 1 + 1 + 5 + 1 + 4?+ 4 = 2 + 5 + 1 + 8;
我們不難理解,不論如何刪去項,我們所得的 鄰間項差的和 總是小于等于n個數(shù)間的 鄰間項差的和,所以只需判斷如何去項能去掉最多的項,并且保持和不變;我們可以看粗 1 2 3 間的鄰間項差的和是 2 = 3 -1;中間的2對結(jié)果并沒有影響,同理也能看出 7 11 13也滿足,但是 3 8 7間卻不滿足;所以說,只有中間的數(shù)夾在兩邊的數(shù)直接,這個數(shù)才對結(jié)果沒有影響,可以刪去,所以運用循環(huán)判斷,計數(shù),并標(biāo)記是否能輸出。
代碼:
#include <iostream> #include <algorithm> #include <cstring> using namespace std;const int maxn = 2e5 + 10;int a[maxn], vis[maxn]; //vis來標(biāo)記能否輸出 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?
總結(jié)
以上是生活随笔為你收集整理的CodeForces #649 B. Most socially-distanced subsequence(思维、规律)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Markdown 公式指导手册
- 下一篇: Java 异常错误 (Ljava/lan