题目来源:码蹄集
题目描述:
Python代码实现:
N = 400005
rec = []
u, v, a = [], [], []
n, m, k = map(int, input().split())
for i in range(n):
row = list(map(int, input().split()))
rec.append(row)
for i in range(m):
u.append(rec[0][i])
for i in range(1, n):
row = sorted(rec[i])
v += row[:k]
for x in u:
for y in v:
a.append(x + y)
a.sort()
u = a[:k]
v = []
a = []
for x in u:
print(x, end=' ')
C++代码实现:
代码参考链接:https://betheme.net/dashuju/49396.html?action=onClick
#include<bits/stdc++.h>
using namespace std;
const int N = 4e5 + 5;
int rec[400][400], n, m, k;
vector<int> a;
vector<int> u, v;
int main() {
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%d", &rec[i][j]);
}
}
for (int i = 1; i <= m; i++) {
u.push_back(rec[1][i]);
}
for (int i = 2; i <= n; i++) {
sort(rec[i] + 1, rec[i] + 1 + m);
for (int j = 1; j <= k; j++) {
v.push_back(rec[i][j]);
}
for (int x: u) {
for (int y: v) {
a.push_back(x + y);
}
}
sort(a.begin(), a.end());
while (u.size() != 0) {
u.pop_back();
}
while (v.size() != 0) {
v.pop_back();
}
for (int i = 0; i < k; i++) {
u.push_back(a[i]);
}
while (a.size() != 0) {
a.pop_back();
}
}
for (int i = 0; i < k; i++) {
printf("%d ", u[i]);
}
return 0;
}
Java代码实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = 400005;
int[][] rec = new int[405][405];
List<Integer> u = new ArrayList<>();
List<Integer> v = new ArrayList<>();
List<Integer> a = new ArrayList<>();
int n, m, k;
n = sc.nextInt();
m = sc.nextInt();
k = sc.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
rec[i][j] = sc.nextInt();
}
}
for (int i = 1; i <= m; i++) {
u.add(rec[1][i]);
}
for (int i = 2; i <= n; i++) {
Arrays.sort(rec[i], 1, m+1);
for (int j = 1; j <= k; j++) {
v.add(rec[i][j]);
}
for (int x: u) {
for (int y: v) {
a.add(x + y);
}
}
Collections.sort(a);
u = new ArrayList<>(a.subList(0, k));
v.clear();
a.clear();
}
for (int i = 0; i < k; i++) {
System.out.print(u.get(i) + " ");
}
}
}