思路是用二维数组存起来,之后按主键排序
插入排序稳定
排序之后把相同主键数据分块一起计算
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main10 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
int index = sc.nextInt();
int transfer = sc.nextInt();
int example = sc.nextInt();
//接收数据
int[][] ints = new int[col][row];
for (int j = 0; j < col; j++) {
for (int i = 0; i < row; i++) {
ints[j][i] = sc.nextInt();
}
}
//只有一行时直接求和输出
if (col == 1) {
int sum = 0;
for (int i = 0; i < row; i++) {
sum += ints[0][i];
}
System.out.println(sum);
} else {
//将转换列放入set中
Set<Integer> set = new HashSet<>();
set.add(ints[0][transfer]);
//对数组进行插入排序
for (int i = 1; i < col; i++) {
set.add(ints[i][transfer]);
int temp[] = new int[row];
for (int j = 0; j < row; j++) {
temp[j] = ints[i][j];
}
while (temp[index] < ints[i - 1][index] && i > 1) {
for (int j = 0; j < row; j++) {
ints[i][j] = ints[i - 1][j];
}
i--;
}
for (int j = 0; j < row; j++) {
ints[i][j] = temp[j];
}
}
//记录总值
int sum = 0;
int su = ints[0][index];
Set<Integer> set1 = new HashSet<>();
set1.add(ints[0][transfer]);
//先计算第一行
for (int i = 0; i < row; i++) {
if (i != transfer) {
sum += ints[0][i];
}
}
for (int i = 1; i < col; i++) {
if (su == ints[i][index]) {
set1.add(ints[i][transfer]);
sum += ints[i][example];
} else {
sum -= (set.size() - set1.size());
set1.clear();
su = ints[i][index];
set1.add(ints[i][transfer]);
//把除转换列的值放入sum
for (int j = 0; j < row; j++) {
if (j != transfer) {
sum += ints[i][j];
}
}
}
}
//减去最后一次的
sum -= (set.size() - set1.size());
System.out.println(sum);
}
}
}
#帆软软件##笔试题目#