第十四届浙江财经大学程序设计竞赛重现赛


A. a sad story

来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

The Great Wall story of Meng Jiangnv’s Bitter Weeping happened during the Qin Dynasty (221BC- 206BC). Meng jiangnv was a beauty in the Qin Dynasty, and she lived happily with her husband. At that time, Emperor Qin Shihuang (the first emperor of Qin) announced to build the Great Wall. And the officials suddenly broke in their happy life and took Meng’s husband away to build the wall. Because of the missing for her husband, she decided to set off to look for her husband. After a long journey, finally she reached the foot of the Great Wall at the present Shanhaiguan Pass. Upon her arrival, a bad news came to her, however, her husband had already died of exhaustion and was buried into the Great Wall! Meng could not help crying. She sat on the ground and cried and cried. Suddenly with a tremendous noise, a 400 kilometer-long (248-mile-long) section of the wall collapsed over her bitter wail.
Today, Qin Shihuang gets N stones. The height of the ith stone is Ai. He will use all these stones to rebuild the Great Wall. In order to make the Great Wall more sturdy, the prime minister Li Si proposes a formula to calculate the “weakness” of the reconstructed Great Wall
         
The Bi is the height of the ith stone in the reconstructed Great Wall, and the K is provided by Li Si.
For example, Qin Shihuang gets 5 stones. The height of these stones are [5,3,2,4,1], and the K is 2. There are 120 different ways to rebuild the Great Wall. The following figures show the two solutions:

The weakness of left figure and right figure are 4 and 11, respectively.

Now, Li Si wants to know the minimum value of “weakness”. Li Si is too old to calculate the answer quickly, so he asks you for help.


2
5 2
1 2 3 4 5
5 3
1 3 2 2 7

Case #1: 4
Case #2: 7

水题,想要知道最小的weakness,就让最大值-次大值

公式意思就是:让你在k长度的区间内,得到最大值-最小值

sort一下,求出和:a[i+k-1]-a[i]


#include <bits/stdc++.h>
using namespace std;
int a[100005];
int main()
{
    int T,ans=0;
    scanf("%d",&T);
    while(T--)
    {
        int n,m,sum=0;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        sort(a+1,a+n+1);
        for(int i=1;i<=n;i++)
        {
            if(i+m-1>n) break;
            sum+=a[i+m-1]-a[i];
        }
        printf("Case #%d: %d\n",++ans,sum);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41037114/article/details/80593163
今日推荐