版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82729056
Description
有N个整数,你要求出这N个数当中前K小的总和。
Input
多组测试数据。
第一行,一个整数G,表示有G组测试数据。1 <= G <= 5。
每组测试数据格式如下:
第一行,N和K。 1 <= N <= 1000。 1 <= K <= N。
第二行,N个整数,每个整数范围【1,1000】。
Output
共G行。每行一个整数。
Sample Input
3
4 2
1 5 3 4
3 3
1 5 4
5 1
2 2 4 5 3
Sample Output
4
10
2
以下二选一
STL是万能的!
STL不是万能的,没有STL是万万不能的!
#include <iostream>
#include <algorithm>
#define SIZE 1010
using namespace std;
int a[SIZE];
int main(int argc, char** argv)
{
int t, n, res, i, k;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &k);
for (i = 1; i <= n; ++i)
{
scanf("%d", &a[i]);
}
sort(a + 1, a + n + 1); // STL万岁!
res = 0;
for (i = 1; i <= k; ++i)
{
res += a[i];
}
printf("%d\n", res);
}
return 0;
}