#97-【排序】課程
阿新 • • 發佈:2018-12-10
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; }