Codeforces Round #636 (Div. 3) D.Constant Palindrome Sum题解

Question: There is an array a of length n (even number), 1=<ai<=k, we can change the value of ai, but it must be within (1, k). Ask us how many elements must be changed at least so that the first n/2 elements satisfy
ai+a(n-i+1)=x.

Example:

4
4 2
1 2 1 2
4 3
1 2 2 1
8 7
6 1 1 7 6 3 4 6
6 6
5 2 6 1 3 4
0
1
4
2

Idea: First consider the situation of violence, the range of x must be (2, 2 k), enumerate x, and then calculate the number of changes that need to be changed for each pair. The complexity of this method is (n k), no doubt, TLE, then we need to optimize this method.
The situation can be divided into three categories: there is no need to change/change one of the numbers/change two numbers.
We can first open an array to store the number of x.
After changing one of the numbers, the range of x is in [min(a[i],a[n-i+1])+1,max(a[i],a[n-i+1])+k] ; So open an array to store at most a number whose sum is in the interval (l, r).
Changing the size of two numbers is (n/2-minus the size of changing at most one)*2.

Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=2e5+5;
int a[MAXN];
int e[MAXN*2];
int c[MAXN*2];
int main()
{
    
    
    int t;
    scanf("%d",&t);
    while(t--)
    {
    
    
        int n,k;
        scanf("%d%d",&n,&k);
        memset(e,0,sizeof e);
        memset(c,0,sizeof c);
        for(int i=1;i<=n;i++)
        {
    
    
            scanf("%d",&a[i]);
        }
        for(int i=1;i<=n/2;i++)
        {
    
    
            e[a[i]+a[n-i+1]]++;
        }
        for(int i=1;i<=n/2;i++)
        {
    
    
            c[min(a[i],a[n-i+1])+1]++;
            c[max(a[i],a[n-i+1])+k+1]--;
        }
        for(int i=3;i<=2*k;i++)
        {
    
    
            c[i]+=c[i-1];
        }
        int ans=MAXN;
        for(int i=2;i<=2*k;i++)
        {
    
    
            ans=min(ans,c[i]-e[i]+2*(n/2-c[i]));
        }
        printf("%d\n",ans);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45755679/article/details/105691721