题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <stdio.h> #include <stdlib.h> void swap(int* a, int* b) { int temp; temp = *b; *b = *a; *a = temp; } int main() { int num; scanf("%d",&num); int* keys = (int*) malloc(num*sizeof(int)); int* values = (int*)malloc(num*sizeof(int)); for(int i=0;i<num;i++) { int index,value; scanf("%d", &index); scanf("%d", &value); keys[i]=index; values[i]=value; } //合并 for(int i=0;i<num;i++) { int index = keys[i]; if(index==-1) continue; for(int j=i+1;j<num;j++) { if(keys[j]==index){ keys[j]=-1; values[i]+=values[j]; values[j] = 0; } } } //冒泡排序 for(int i=0;i<num-1;i++) { int index = keys[i]; for(int j=0;j<num-i-1;j++) { if(keys[j]>keys[j+1]){ swap(keys+j,keys+j+1); swap(values+j,values+j+1); } } } for(int i=0;i<num;i++) { if(keys[i]<0) continue; else printf("%d %d\n",keys[i],values[i]); } free(keys); free(values); return 0; }