题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
最笨方法:
1.获取输入数组
2.用index进行排序
3.将相同index的数值进行相加
4.输出不同index的index和数据。
以下是代码:
#include<stdio.h> #include<stdlib.h> typedef struct { int index; int data; }daT; int main(void){ int num =0; int i,j,step; daT tmp = {0,0}; daT *ptr = NULL; scanf("%d", &num); //printf("---------%d\n", num); unsigned int* dataBase = (unsigned int*)malloc(sizeof(int)*2*num); ptr =(daT*) dataBase; memset(dataBase, 0, sizeof(int)*2*num); for(i=0; i< num; i++){ scanf("%d %d", dataBase+2*i, dataBase+2*i+1); } //just maopao for(i=0; i < num; i++) { for(j=0; j < num-i-1; j++){ if((ptr+j)->index > (ptr+j+1)->index){ memcpy(&tmp, ptr+j, sizeof(daT)); memcpy(ptr+j, ptr+j+1, sizeof(daT)); memcpy(ptr+j+1, &tmp, sizeof(daT)); } } } //just hebing for(i= 0; i <num; i=i+step+1){ step =0; for(j=i+1; j<num; j++){ if((ptr+i)->index == (ptr+j)->index ){ (ptr+i)->data += (ptr+j)->data; step++; }else{ break; } } } //output i = 0; do{ if(i == 0) { printf("%d %d\n", ptr->index, ptr->data); }else{ if((ptr+i)->index != (ptr+i-1)->index) { printf("%d %d\n", (ptr+i)->index, (ptr+i)->data); } } i++; }while(i< num); if(dataBase) free(dataBase); return 0; }