题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct hash_s{
int key;
int value;
}hash_t;
int compare_fun(const void *arg1, const void *arg2)
{
hash_t *tmp1, *tmp2;
tmp1 = (hash_t *)arg1;
tmp2 = (hash_t *)arg2;
//printf("k1[%d], v[%d] k[%d], v[%d] \n", tmp1->key, tmp1->value, tmp2->key, tmp2->value);
return tmp1->key - tmp2->key;
}
int main() {
int n, i;
hash_t map[500];
memset(map, 0, sizeof(hash_t) * 500);
scanf("%d", &n);
/* 输入 */
for(i = 0; i < n; i++){
scanf("%d %d", &map[i].key, &map[i].value);
//printf("%d %d\n", map[i].key, map[i].value);
}
/* 快排 */
qsort(map, n, sizeof(hash_t), compare_fun);
for(i = 0; i < n; i++){
//printf("%d %d\n", map[i].key, map[i].value);
}
/* 合并,相同的存在后面一个,最后一个单独打印 */
for(i = 1; i < n; i++) {
if (map[i-1].key == map[i].key) {
map[i].value += map[i-1].value;
} else {
printf("%d %d\n", map[i-1].key, map[i-1].value);
}
}
printf("%d %d\n", map[n-1].key, map[n-1].value);
return 0;
}