1. 程式人生 > 其它 >牛客程式設計題(C語言):HJ8 合併表記錄

牛客程式設計題(C語言):HJ8 合併表記錄

https://www.nowcoder.com/exam/oj/ta?tpId=37

https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201

提交程式碼

#include <stdio.h>

typedef struct node{
    int ind;
    int val;
}node_t;

int main(void){
    int i, j;
    int n;
    int top;
    node_t nodes[256];
    while(scanf("%d", &n) == 1){
        int val, ind;
        top = 0;
        scanf("%d %d", &nodes[top].ind, &nodes[top].val);
        for(i = 1; i < n; ++i){
            scanf("%d %d", &ind, &val);
            for(j = top; j >= 0; --j){
                if(nodes[j].ind == ind){
                    nodes[j].val += val;
                    break;
                }
            }
            if(j < 0){
                for(j = top; j >=0 && nodes[j].ind > ind; --j){
                    nodes[j + 1] = nodes[j];
                }
                nodes[j + 1].ind = ind;
                nodes[j + 1].val = val;
                ++top;
            }
        }
        for(i = 0; i <= top; ++i){
            printf("%d %d\n", nodes[i].ind, nodes[i].val);
        }
    }
    return 0;
}

執行結果

參考:https://blog.csdn.net/faramita_of_mine/article/details/124656679