题解 | 合并表记录
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <stdio.h>
typedef struct {
int index;
int val;
int is_valid;
} keyVal;
int main() {
int n;
while (scanf("%d", &n) !=EOF) {
keyVal tem[n], t;
for (int i = 0; i < n; i++) {
scanf("%d%d", &tem[i].index, &tem[i].val);
tem[i].is_valid = 1;
}
for (int i = 0; i < n; i++) {
if (!tem[i].is_valid) continue;
for (int j = i + 1; j < n; j++) {
if (tem[j].index == tem[i].index && tem[j]. is_valid) {
tem[i].val += tem[j].val;
tem[j].is_valid = 0;
}
}
}
for (int i = 0; i < n-1; i++) {
if (!tem[i].is_valid) continue;
for (int j = i+1; j < n; j++) {
if (tem[j].is_valid && tem[i].index > tem[j].index) {
t = tem[i];
tem[i] = tem[j];
tem[j] = t;
}
}
}
for (int i = 0; i < n; i++) {
if (tem[i].is_valid) {
printf("%d %d\n", tem[i].index, tem[i].val);
}
}
}
return 0;
}
查看18道真题和解析