题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct{ int index; int value; char del; }item_t; int cmp(const void *a, const void *b) { item_t *it1 = (item_t *)a; item_t *it2 = (item_t *)b; return (it1->index - it2->index); } int main() { unsigned int n = 0; scanf("%u", &n); item_t *table = malloc(sizeof(item_t)*n); memset(table,0, sizeof(sizeof(item_t)*n)); int i = 0; for (i = 0; i < n; i++) { scanf("%u %u", &table[i].index, &table[i].value); } //相同index的 value加到第一个出现的index的表项 for (i = 0; i < n; i++) { int j = 0; for (j = i+1; j < n; j++) { if (table[j].del == 0 && table[j].index == table[i].index) { table[i].value += table[j].value; table[j].del = 1;//表示盖表项被软删 } } } //要求输出要按序,所以先排序 qsort(table, n, sizeof(item_t), cmp); //输出没有被删除的表项 for (i = 0; i < n; i++) { if (table[i].del == 0 ) { printf("%d %d\n", table[i].index, table[i].value); } } }
收获点:
1.樯橹灰飞烟灭