题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <stdio.h> typedef struct Table { int idx; int val; } table; int main() { int n, a, b, i = 0, j = 0, tmp; scanf("%d", &n); table tbl[n]; //printf("sizeof(tbl)=%ld %ld %ld\n", sizeof(tbl), sizeof(table), sizeof(int)); while (scanf("%d %d", &a, &b) != EOF) { tbl[i].idx = a; tbl[i].val = b; //printf("tbl[%d]=%d %d\n", i, tbl[i].idx, tbl[i].val); i++; } for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (tbl[i].idx == tbl[j].idx) { tbl[i].val += tbl[j].val; tbl[j].val = 0; //printf("i tbl[%d]=%d %d\n", i, tbl[i].idx, tbl[i].val); //printf("j tbl[%d]=%d %d\n", j, tbl[j].idx, tbl[j].val); } } } for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (tbl[i].idx > tbl[j].idx) { tmp = tbl[i].idx; tbl[i].idx = tbl[j].idx; tbl[j].idx = tmp; tmp = tbl[i].val; tbl[i].val = tbl[j].val; tbl[j].val = tmp; } } } for (i = 0; i < n; i++){ //printf("tbl[%d]=%d %d\n", i, tbl[i].idx, tbl[i].val); if(tbl[i].val != 0) printf("%d %d\n", tbl[i].idx, tbl[i].val); } return 0; }