Odd Subarrays (贪心,dp一下)(CF 794 d2)

 Odd Subarrays
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
For an array [b1,b2,…,bm] define its number of inversions as the number of pairs (i,j) of integers such that 1≤i<j≤m and bi>bj. Let's call array b odd if its number of inversions is odd.

For example, array [4,2,7] is odd, as its number of inversions is 1, while array [2,1,4,3] isn't, as its number of inversions is 2.

You are given a permutation [p1,p2,…,pn] of integers from 1 to n (each of them appears exactly once in the permutation). You want to split it into several consecutive subarrays (maybe just one), so that the number of the odd subarrays among them is as large as possible.

What largest number of these subarrays may be odd?

Input
The first line of the input contains a single integer t (1≤t≤105)  — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤105)  — the size of the permutation.

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

The sum of n over all test cases doesn't exceed 2⋅105.

Output
For each test case output a single integer  — the largest possible number of odd subarrays that you can get after splitting the permutation into several consecutive subarrays.

Example
inputCopy
5
3
1 2 3
4
4 3 2 1
2
1 2
2
2 1
6
4 5 6 1 2 3
outputCopy
0
2
0
1
1
Note
In the first and third test cases, no matter how we split our permutation, there won't be any odd subarrays.

In the second test case, we can split our permutation into subarrays [4,3],[2,1], both of which are odd since their numbers of inversions are 1.

In the fourth test case, we can split our permutation into a single subarray [2,1], which is odd.

In the fifth test case, we can split our permutation into subarrays [4,5],[6,1,2,3]. The first subarray has 0 inversions, and the second has 3, so it is odd.
View Code

思路:

  • 要求子集个数最大,这种最大,最小可以用贪心思想,然 |子集| 的值尽量小, 
  • 只要看相邻大就行了, 隔空成立,那么在某个相邻也一定成立 (贪心思想)
  • 最后dp一下就行了
#include <bits/stdc++.h>
using namespace std;
#define ri register int
#define  M 100005
// 15:20
template <class G> void read(G &x)
{
    x=0;int f=0;char ch=getchar();
    while(ch<'0'||ch>'9'){f=ch=='-';ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    x=f?-x:x;
    return ;
}


int n,m;
int val[M];
int dp[M];
int main(){
    
    int t;
    read(t);
    while(t--)
    {
        read(n);
        for(ri i=0;i<=n;i++) dp[i]=0;
        for(ri i=1;i<=n;i++)
        {
            read(val[i]);
            if(val[i-1]>val[i])
            {
                dp[i]=max(dp[i-2]+1,dp[i-1]);
            }
            else dp[i]=dp[i-1];
        }
        printf("%d\n",dp[n]);
    }
    return 0;
    
    
    
    
}
View Code

 

posted @ 2022-06-06 10:33  VxiaohuanV  阅读(61)  评论(0编辑  收藏  举报