B. Sum of Medians (Thinking + Mathematics)

https://codeforces.com/contest/1440/problem/B


Question: Divide the sequence, find the sum of the median in each block, and construct the largest one.

Idea: When n=2, n/2=1, greedy takes 2 from the front to the back, and does not waste the large numbers behind.

When n>2, for example, n=3. Take 1 at the front and 2 at the back, the most greedy.

When n=4, n/2=2; so there is 1 in the front and 3 in the back. The median is on the big side.

When n/5=, n/2=3, 2 in the front and 3 in the back. The median is on the big side.

Then sweep forward after O(n)

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e6+100;
typedef long long LL;
LL a[maxn];
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL t;cin>>t;
  while(t--){
     LL n,k;cin>>n>>k;
     LL sum=0;LL ans=0;
     for(LL i=1;i<=n*k;i++) cin>>a[i];
     if(n==2){
       for(LL i=1;i<=n*k;i+=n){
        if(ans>=k){
            break;
            }
        sum+=a[i];ans++;
        }
        cout<<sum<<endl;
     }
     else{
        LL st=0;
        if(n%2==0) st=n/2+1;
        else st=ceil(1.0*n/2.0);
        for(LL i=n*k-(st-1);i>=1;i-=st){
            if(ans>=k){
                break;
            }
         ///   cout<<a[i]<<" ";
            sum+=a[i];ans++;
        }
        cout<<sum<<endl;
     }
  }
return 0;
}

 

Guess you like

Origin blog.csdn.net/zstuyyyyccccbbbb/article/details/109807689