题解 | 合并表记录

#include <stdio.h>
#include <stdlib.h>

typedef struct sqlist {
    int index;
    int data;
    int tag;
} sqlist, *list;
void swap(list indexsql,int i,int j){
    int temindex,temdata;
    temindex = (indexsql + i)->index;
    temdata = (indexsql + i)->data;
    (indexsql + i)->index = (indexsql + j)->index;
    (indexsql + i)->data = (indexsql + j)->data;
    (indexsql + j)->index = temindex;
    (indexsql + j)->data = temdata;
}
void quick_sort_sql(list indexsql,int low,int high){
    if(low < high){
        int i = low;
        int j = high;
        int temindex = (indexsql+i)->index;
        int temdata = (indexsql+i)->data;
        while(i < j){
            while(i < j && (indexsql + j)->index >= temindex){
                j--;
            }
            swap(indexsql,i,j);
            while(i < j && (indexsql + i)->index <= temindex){
                i++;
            }
            swap(indexsql,i,j);
        }
        (indexsql + i)->index = temindex;
        (indexsql + i)->data = temdata;
        quick_sort_sql(indexsql, low, i - 1);
        quick_sort_sql(indexsql, i + 1, high);
    }
}
void print_sql(list indexsql,int n){
    int i = 0;
    int j;
    for(i = 0;i < n;i++){
        for(j = i + 1;j < n;j++){
            if((indexsql + j)->tag == 0 &&(indexsql + j)->index == (indexsql + i)->index){
                (indexsql + i)->data += (indexsql + j)->data;
                (indexsql + j)->tag = 1; 
            }
        }
        if((indexsql + i)->tag == 0){
        printf("%d %d\n",(indexsql + i)->index,(indexsql + i)->data);}
    }
    
}
int main() {
    int n, i;
    scanf("%d", &n);
    list indexsql;
    indexsql = (sqlist*)malloc(sizeof(sqlist) * n);
    for (i = 0; i < n; i++) {
        (indexsql + i)->tag = 0;
        scanf("%d %d", &(indexsql + i)->index, &(indexsql + i)->data);
    }
    quick_sort_sql(indexsql, 0, n - 1);
    print_sql(indexsql,n);
    //swap(indexsql, 0, 3);
    /*for(i = 0;i < n;i++){
        printf("%d %d\n",(indexsql + i)->index, (indexsql + i)->data);
    }*/
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务