NC15329. A Sad Story
描述
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.
输入描述
The first line contains an integer T, where T is the number of test cases. T test cases follow.
For each test case, the first line contains two integers N and K, where N is the number of stones and K is a variable which provided by Li Si.The second line contains N integers A1, A2, ... , AN, where Ai is the height of the ith stone that QinShiHuang gets.• 1 ≤ T ≤ 50.
• 1 ≤ N ≤ 103.• 1 ≤ K ≤ N.• 1≤ Ai ≤104.
输出描述
For each test case, print one line containing “Case #x: y”, where x is the test case number (starting from 1) and y is the minimum value of “weakness”.
示例1
输入:
2 5 2 1 2 3 4 5 5 3 1 3 2 2 7
输出:
Case #1: 4 Case #2: 7
C++(clang++11) 解法, 执行用时: 9ms, 内存消耗: 428K, 提交时间: 2021-07-21 14:13:23
#include <bits/stdc++.h> using namespace std; int t,n,cas,k,a[1010]; int main() { scanf("%d",&t); while(t--) { scanf("%d %d",&n,&k); for(int i=1;i<=n;i++) scanf("%d",&a[i]); sort(a+1,a+n+1); int ans=0;cas++; for(int i=1;i<=n-k+1;i++) ans+=a[i+k-1]-a[i]; printf("Case #%d: %d\n",cas,ans); } }
Python3 解法, 执行用时: 67ms, 内存消耗: 4824K, 提交时间: 2022-10-25 14:40:07
T=int(input()) for _ in range(T): n,k=map(int,input().split()) A=list(map(int,input().split())) A=sorted(A) print('Case #'+str(_+1)+':',sum(A[k-1:])-sum(A[:n-k+1]))